本文整理汇总了Python中xml.etree.cElementTree.fromstring函数的典型用法代码示例。如果您正苦于以下问题:Python fromstring函数的具体用法?Python fromstring怎么用?Python fromstring使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了fromstring函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _parse
def _parse(self):
out = io.BytesIO()
with io.open(self.resource_file, mode='rb') as f:
out.write(xor(bytearray(f.read())))
try:
temp = zipfile.ZipFile(out)
except zipfile.BadZipfile:
raise zipfile.BadZipfile
if self.alias in temp.namelist():
gw_info = xor(bytearray(temp.read(self.alias)))
else:
raise ValueError('Invalid alias {0} for resource file {1}, {2}'.format(self.alias,
os.path.basename(self.resource_file),
temp.namelist()))
# PY 3
try:
xml = et.fromstring(gw_info)
except TypeError:
xml = et.fromstring(str(gw_info))
for node in xml:
if node.tag in self.gw:
self.gw[node.tag] = node.text or ''
示例2: test_rpm
def test_rpm(self):
namespaces = [
utils.Namespace('rpm', primary.RPM_SPEC_URL),
]
raw_xml = utils.element_to_raw_xml(self.rpm_element, namespaces, primary.COMMON_SPEC_URL)
# make sure it stripped out any namespace declarations and root elements
self.assertTrue(re.match(r'^<package +type="rpm">', raw_xml))
# make sure there are no stray closing elements, like </metadata>
self.assertTrue(raw_xml.rstrip().endswith('</package>'))
# make sure it preserved the "rpm" prefix
self.assertTrue(re.search(r'<rpm:license *>GPLv2</rpm:license>', raw_xml))
# make sure it got the requires and provides entries
self.assertTrue(raw_xml.find('dolphin') >= 0)
self.assertTrue(raw_xml.find('penguin') >= 0)
# these should all be stripped out
self.assertTrue(raw_xml.find('xmlns') == -1)
# had this problem on python 2.6 where it treated the default namespace
# as a namespace with prefix ''
self.assertTrue(raw_xml.find('<:') == -1)
# try to re-parse the XML to make sure it's valid. fake tag is necessary
# to declare the prefix "rpm"
fake_xml = '<fake xmlns:rpm="http://pulpproject.org">%s</fake>' % raw_xml
# fromstring just to make sure this is valid
ET.fromstring(fake_xml)
示例3: main
def main():
if len(sys.argv) == 1:
stream = sys.stdin
doc = etree.fromstring(stream.read())
stream.close()
base = None
else:
src = sys.argv[1]
if ":" in src:
stream = urllib2.urlopen(src)
base = src
doc = etree.fromstring(stream.read())
stream.close()
else:
with open(src) as stream:
doc = etree.fromstring(stream.read())
base = "file:/"+src
if doc.tag != rif.Document:
error(doc, "Root element is not rif:Document.")
if base:
focus = LabeledNode(focus)
else:
focus = BlankNode()
(focus, triples) = describe(doc, focus, base)
print "# RIF focus is", focus.as_turtle()
print "# %d triples" % len(triples)
for (s,p,o) in triples:
print s.as_turtle(), "<"+p+">", o.as_turtle(),"."
示例4: check_source_in_project
def check_source_in_project(self, project, package, verifymd5, deleted=False):
self._fill_package_list(project)
if not deleted and not package in self.packages[project]:
return None, None
his = self.get_package_history(project, package, deleted)
if his is None:
return None, None
his = ET.fromstring(his)
historyrevs = dict()
revs = list()
for rev in his.findall('revision'):
historyrevs[rev.find('srcmd5').text] = rev.get('rev')
revs.append(rev.find('srcmd5').text)
revs.reverse()
for i in range(min(len(revs), 5)): # check last commits
srcmd5=revs.pop(0)
root = self.cached_GET(makeurl(self.apiurl,
['source', project, package], { 'rev': srcmd5, 'view': 'info'}))
root = ET.fromstring(root)
if root.get('verifymd5') == verifymd5:
return srcmd5, historyrevs[srcmd5]
return None, None
示例5: test_integration
def test_integration(self):
print("Start Integration-Tests")
test_context = self.get_testcontext(self.env)
command_package = ["swid_generator", "swid", "--full", "--pretty", "--package", test_context['package_name']]
output_swid_tag = self.get_tree_output_from_cmd(command_package)
expected_swid_tag = test_context['template_full_pretty_cmd_package']
self.check_equality(expected_swid_tag, output_swid_tag)
command_swid = ["swid_generator", "swid", "--pretty", "--package", test_context['package_name']]
output_swid_tag = self.get_tree_output_from_cmd(command_swid)
expected_swid_tag = test_context['template_no_payload_cmd_package']
self.check_equality(expected_swid_tag, output_swid_tag)
command_package = "swid_generator swid --pretty --full --package {PACKAGE} --pkcs12 {CERTIFICATE} --pkcs12-pwd R4onQ7UdCbDoFPeH"
command_package = command_package.format(CERTIFICATE=test_context['certificate'], PACKAGE=test_context['package_name'])
output_swid_tag = self.get_string_output_from_cmd(command_package.split(' '))
expected_swid_tag = test_context['template_full_pretty_signed_cmd_package']
self.validate_signature(output_swid_tag)
self.check_equality(expected_swid_tag, ET.fromstring(output_swid_tag))
command_package_file = "swid_generator swid --full --pretty --package-file {PACKAGE_FILE}"
command_package_file = command_package_file.format(PACKAGE_FILE=test_context['package_path'])
output_swid_tag = self.get_tree_output_from_cmd(command_package_file.split(' '))
expected_swid_tag = test_context['template_full_pretty_cmd_package_file']
self.check_equality(expected_swid_tag, output_swid_tag)
command_package_file = "swid_generator swid --pretty --package-file {PACKAGE_FILE}"
command_package_file = command_package_file.format(PACKAGE_FILE=test_context['package_path'])
output_swid_tag = self.get_tree_output_from_cmd(command_package_file.split(' '))
expected_swid_tag = test_context['template_no_payload_cmd_package_file']
self.check_equality(expected_swid_tag, output_swid_tag)
command_package_file = "swid_generator swid --pretty --full --package-file {PACKAGE_FILE} --pkcs12 {CERTIFICATE} --pkcs12-pwd R4onQ7UdCbDoFPeH"
command_package_file = command_package_file.format(CERTIFICATE=test_context['certificate'], PACKAGE_FILE=test_context['package_path'])
output_swid_tag = self.get_string_output_from_cmd(command_package_file.split(' '))
expected_swid_tag = test_context['template_full_pretty_signed_cmd_package_file']
self.validate_signature(output_swid_tag)
self.check_equality(expected_swid_tag, ET.fromstring(output_swid_tag))
# Prepare Folders and Files for evidence
self.create_folder("/tmp/evidence-test")
self.create_folder("/tmp/evidence-test/sub1")
self.create_folder("/tmp/evidence-test/sub2")
self.create_folder("/tmp/evidence-test/sub3")
self.touch("/tmp/evidence-test/sub1/testfile1")
self.touch("/tmp/evidence-test/sub1/testfile2")
self.touch("/tmp/evidence-test/sub2/testfile2")
self.touch("/tmp/evidence-test/sub3/testfile3")
command_evidence = "swid_generator swid --full --pretty --evidence {EVIDENCE_PATH} --name evidence --version-string 1.0"
command_evidence = command_evidence.format(EVIDENCE_PATH=test_context['evidence_test_folder'])
output_swid_tag = self.get_tree_output_from_cmd(command_evidence.split(' '))
expected_swid_tag = test_context['template_evidence']
self.check_equality(expected_swid_tag, output_swid_tag)
示例6: test_merge_1
def test_merge_1(self):
root= et.fromstring(xml_file5)
x= merge(root)
y= et.fromstring(xml_file6)
z=et.tostring(y)
string = et.tostring(x)
self.assert_(string == z)
示例7: to_xml
def to_xml(obj, root="object", pretty=False, header=True, dasherize=True):
"""Convert a dictionary or list to an XML string.
Args:
obj: The dictionary/list object to convert.
root: The name of the root xml element.
pretty: Whether to pretty-format the xml (default False).
header: Whether to include an xml header (default True).
dasherize: Whether to convert underscores to dashes in
attribute names (default True).
Returns:
An xml string.
"""
root = dasherize and root.replace("_", "-") or root
root_element = ET.Element(root)
if isinstance(obj, list):
root_element.set("type", "array")
for i in obj:
element = ET.fromstring(to_xml(i, root=singularize(root), header=False))
root_element.append(element)
else:
for key, value in obj.iteritems():
key = dasherize and key.replace("_", "-") or key
if isinstance(value, dict) or isinstance(value, list):
element = ET.fromstring(to_xml(value, root=key, header=False))
root_element.append(element)
else:
element = ET.SubElement(root_element, key)
serialize(value, element)
if pretty:
xml_pretty_format(root_element)
xml_data = ET.tostring(root_element)
if header:
return XML_HEADER + "\n" + xml_data
return xml_data
示例8: __new__
def __new__(cls,tag,thing = None,*args,**kwargs):
if hasattr(tag,'__xml__'):
return tag.__xml__()
self = object.__new__(xml)
if cElementTree.iselement(tag):
self.__content = tag
elif isinstance(tag,cElementTree.ElementTree):
self.__content = tag.getroot()
elif is_file(tag):
self.__content = cElementTree.parse(tag).getroot()
elif isinstance(tag,str) and len(tag) > 0 and tag[0] == '<':
self.__content = cElementTree.fromstring(tag)
else:
if type(tag) != str:
raise TypeError("Cannot convert %s object to xml" % str(type(tag)))
self.__content = cElementTree.fromstring('<%s/>' % tag)
if is_text(thing) or type(thing) == int:
self.__content.text = text(thing)
elif thing != None:
self.append(xml(thing))
for subthing in args:
self.append(xml(subthing))
for key,value in kwargs.items():
if key == '__class' or key == 'klass':
self['class'] = value
else:
self[key] = value
if '{' in self.__content.tag:
self.__prefix = PREFIX_PAT.search(self.__content.tag).groups()[0]
else:
self.__prefix = ''
return self
示例9: xml
def xml(self):
b = etree.TreeBuilder()
b.start('post', {'id':self.id})
b.start('title',{})
b.data(escape(self.title))
b.end('title')
b.start('author',{})
b.data(escape(self.author))
b.end('author')
b.start('date',{})
b.data(str(time.mktime(self.date.timetuple())))
b.end('date')
b.start('text',{})
b.data(escape(self.text))
b.end('text')
b.end('post')
tag = b.close()
# Sanity check to make sure that etree will allow us
# to parse this again later.
f = StringIO()
etree.ElementTree(tag).write(f)
etree.fromstring(f.getvalue())
return tag
示例10: getIDs
def getIDs(self, queryURL, maxHits=0):
ids = []
cnt = 1
# first batch of results
result = self.dispatchRequest(queryURL)
t = tree.fromstring(result)
ids.extend([x.text for x in t.find('IdList').findall('Id')])
hits = int(t.find('Count').text)
print 'Total hits: ', hits
print 'batch: %d, got: %d' % (cnt, len(ids))
# if we have enough already
if maxHits > 0 and (len(ids) > maxHits or maxHits > hits):
return ids[:maxHits]
# if there are more, get them also with retstart option
while len(ids) < hits:
nq = queryURL + '&retstart=%d&retmax=%d' % (len(ids), self.maxdoc)
result = self.dispatchRequest(nq)
t = tree.fromstring(result)
ids.extend([x.text for x in t.find('IdList').findall('Id')])
cnt += 1
print 'batch: %d, total: %d' % (cnt, len(ids))
if maxHits and len(ids) >= maxHits:
break
#end
if maxHits:
return ids[:maxHits]
else:
return ids
示例11: syncAllTask
def syncAllTask(request):
# 记录ccd的任务
an = AssignNotify()
an.watch('cdchu')
usrlist = UserList().getLogUsersNameList()
host = "172.16.144.11"
url = "/itsm/Service1.asmx/GetTaskList?users=" + "|".join(usrlist)
conn = httplib.HTTPConnection(host)
conn.request("GET", url)
res = conn.getresponse()
xl = ET.fromstring(res.read())
con = ET.fromstring(xl.text.encode("utf-8"))
contentList = xml2Python(con)
cursor = connection.cursor()
transaction.commit_unless_managed()
cursor.execute("truncate table dfat_smtasklist")
for key in contentList:
addNew(key,smtasklist)
conn.close()
# 检查并通知
an.notify('[email protected];[email protected]', usrlist)
return HttpResponse("ok")
示例12: run
def run(self):
while True:
drives = {}
p = subprocess.Popen(["system_profiler", "SPUSBDataType", "-xml"], stdout=subprocess.PIPE)
xml = ElementTree.fromstring(p.communicate()[0])
p.wait()
xml = self._parseStupidPListXML(xml)
for dev in self._findInTree(xml, "Mass Storage Device"):
if "removable_media" in dev and dev["removable_media"] == "yes" and "volumes" in dev and len(dev["volumes"]) > 0:
for vol in dev["volumes"]:
if "mount_point" in vol:
volume = vol["mount_point"]
drives[os.path.basename(volume)] = volume
p = subprocess.Popen(["system_profiler", "SPCardReaderDataType", "-xml"], stdout=subprocess.PIPE)
xml = ElementTree.fromstring(p.communicate()[0])
p.wait()
xml = self._parseStupidPListXML(xml)
for entry in xml:
if "_items" in entry:
for item in entry["_items"]:
for dev in item["_items"]:
if "removable_media" in dev and dev["removable_media"] == "yes" and "volumes" in dev and len(dev["volumes"]) > 0:
for vol in dev["volumes"]:
if "mount_point" in vol:
volume = vol["mount_point"]
drives[os.path.basename(volume)] = volume
self.drivesChanged.emit(drives)
time.sleep(5)
示例13: _process_case_block
def _process_case_block(domain, case_block, attachments, old_case_id):
def get_namespace(element):
m = re.match('\{.*\}', element.tag)
return m.group(0)[1:-1] if m else ''
def local_attachment(attachment, old_case_id, tag):
mime = attachment['server_mime']
size = attachment['attachment_size']
src = attachment['attachment_src']
cached_attachment = get_cached_case_attachment(domain, old_case_id, tag)
attachment_meta, attachment_stream = cached_attachment.get()
return UploadedFile(attachment_stream, src, size=size, content_type=mime)
# Remove namespace because it makes looking up tags a pain
root = ET.fromstring(case_block)
xmlns = get_namespace(root)
case_block = re.sub(' xmlns="[^"]+"', '', case_block, count=1)
root = ET.fromstring(case_block)
tag = "attachment"
xml_attachments = root.find(tag)
ret_attachments = {}
if xml_attachments:
for attach in xml_attachments:
attach.attrib['from'] = 'local'
attach.attrib['src'] = attachments[attach.tag]['attachment_src']
ret_attachments[attach.attrib['src']] = local_attachment(attachments[attach.tag], old_case_id, attach.tag)
# Add namespace back in without { } added by ET
root.attrib['xmlns'] = xmlns
return ET.tostring(root), ret_attachments
示例14: doit
def doit(args) :
ofile1 = args.outfile1
ofile2 = args.outfile2
ofile3 = args.outfile3
xmlstring = "<item>\n<subitem hello='world'>\n<subsub name='moon'>\n<value>lunar</value>\n</subsub>\n</subitem>"
xmlstring += "<subitem hello='jupiter'>\n<subsub name='moon'>\n<value>IO</value>\n</subsub>\n</subitem>\n</item>"
# Using etutil's xmlitem class
xmlobj = etutil.xmlitem()
xmlobj.etree = ET.fromstring(xmlstring)
etwobj = etutil.ETWriter(xmlobj.etree)
etwobj.serialize_xml(xmlobj.write_to_xml)
ofile1.write(xmlobj.outxmlstr)
# Just using ETWriter
etwobj = etutil.ETWriter( ET.fromstring(xmlstring) )
etwobj.serialize_xml(ofile2.write)
# Changing parameters
etwobj = etutil.ETWriter( ET.fromstring(xmlstring) )
etwobj.indentIncr = " "
etwobj.indentFirst = ""
etwobj.serialize_xml(ofile3.write)
# Close files and exit
ofile1.close()
ofile2.close()
ofile3.close()
return
示例15: get_volumes
def get_volumes():
cmd = globalvars.cmd
executor = globalvars.executor
volume_cmd = cmd.get_volume_command()
res = executor.execute(volume_cmd.get_info())
root = ElementTree.fromstring(res)
volumes_xml = root.find("volInfo").find("volumes").findall("volume")
volumes = list()
for volume_xml in volumes_xml:
volume = None
volume_info = Volume.with_volume_info(volume_xml)
# Check whether the volume is up or not
if volume_info.status:
volume_cmd = cmd.get_volume_command().get_volume(volume_info.name).get_status(VolumeStatusOption.DETAIL)
res = executor.execute(volume_cmd)
root = ElementTree.fromstring(res)
volume_xml = root.find("volStatus").find("volumes").find("volume")
volume_status = Volume.with_volume_status(volume_xml)
volume = Volume.merge(volume_status, volume_info)
else:
volume = volume_info
volumes.append(volume)
return Response(
response=json.dumps(volumes, default=Volume.to_json),
mimetype="application/json"
)