本文整理汇总了Python中xml.etree.cElementTree.fromstring函数的典型用法代码示例。如果您正苦于以下问题:Python fromstring函数的具体用法?Python fromstring怎么用?Python fromstring使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了fromstring函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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 ''
开发者ID:EmadMokhtar,项目名称:e24PaymentPipe,代码行数:26,代码来源:e24PaymentPipe.py
示例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)
开发者ID:BrnoPCmaniak,项目名称:pulp_rpm,代码行数:26,代码来源:test_util.py
示例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(),"."
开发者ID:mpetyx,项目名称:pyrif,代码行数:30,代码来源:tr.py
示例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
开发者ID:dirkmueller,项目名称:osc-plugin-factory,代码行数:26,代码来源:manager_42.py
示例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)
开发者ID:strongswan,项目名称:swidGenerator,代码行数:60,代码来源:integration_test.py
示例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)
开发者ID:cs327e,项目名称:cs327e-wcdb3-tests,代码行数:7,代码来源:ajw2232-TestWCDB3.py
示例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
开发者ID:wandenberg,项目名称:pyactiveresource,代码行数:35,代码来源:util.py
示例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
开发者ID:bhramoss,项目名称:code,代码行数:32,代码来源:recipe-576445.py
示例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
开发者ID:saffsd,项目名称:forum_features,代码行数:28,代码来源:DataModel.py
示例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
开发者ID:Alshak,项目名称:clowdflows,代码行数:32,代码来源:NCBI.py
示例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")
开发者ID:laughgege,项目名称:backup-some-code,代码行数:31,代码来源:backgroundSync.py
示例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)
开发者ID:johntron,项目名称:Uranium,代码行数:32,代码来源:OSXRemovableDrives.py
示例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
开发者ID:kkrampa,项目名称:commcare-hq,代码行数:32,代码来源:utils.py
示例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
开发者ID:moyogo,项目名称:pysilfont,代码行数:35,代码来源:xmlDemo.py
示例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"
)
开发者ID:opelhoward,项目名称:gdash,代码行数:28,代码来源:volumes.py
示例16: _sendNMJ
def _sendNMJ(self, host):
"""
Send a NMJ update command to the specified machine
host: The hostname/IP to send the request to (no port)
database: The database to send the request to
mount: The mount URL to use (optional)
return: True if the request succeeded, False otherwise
"""
# if a host is provided then attempt to open a handle to that URL
try:
url_scandir = 'http://' + host + ':8008/metadata_database?arg0=update_scandir&arg1=' + app.NMJv2_DATABASE + '&arg2=&arg3=update_all'
log.debug(u'NMJ scan update command sent to host: {0}', host)
url_updatedb = 'http://' + host + ':8008/metadata_database?arg0=scanner_start&arg1=' + app.NMJv2_DATABASE + '&arg2=background&arg3='
log.debug(u'Try to mount network drive via url: {0}', host)
prereq = Request(url_scandir)
req = Request(url_updatedb)
handle1 = urlopen(prereq)
response1 = handle1.read()
time.sleep(0.3)
handle2 = urlopen(req)
response2 = handle2.read()
except IOError as error:
log.warning(u'Warning: Unable to contact popcorn hour on host {0}: {1}', host, error)
return False
try:
et = etree.fromstring(response1)
result1 = et.findtext('returnValue')
except SyntaxError as error:
log.error(u'Unable to parse XML returned from the Popcorn Hour: update_scandir, {0}', error)
return False
try:
et = etree.fromstring(response2)
result2 = et.findtext('returnValue')
except SyntaxError as error:
log.error(u'Unable to parse XML returned from the Popcorn Hour: scanner_start, {0}', error)
return False
# if the result was a number then consider that an error
error_codes = ['8', '11', '22', '49', '50', '51', '60']
error_messages = ['Invalid parameter(s)/argument(s)',
'Invalid database path',
'Insufficient size',
'Database write error',
'Database read error',
'Open fifo pipe failed',
'Read only file system']
if int(result1) > 0:
index = error_codes.index(result1)
log.error(u'Popcorn Hour returned an error: {0}', error_messages[index])
return False
else:
if int(result2) > 0:
index = error_codes.index(result2)
log.error(u'Popcorn Hour returned an error: {0}', error_messages[index])
return False
else:
log.info(u'NMJv2 started background scan')
return True
开发者ID:pymedusa,项目名称:SickRage,代码行数:60,代码来源:nmjv2.py
示例17: create_etree
def create_etree(self, url):
content = self.get_content(url)
try:
etree = ET.fromstring(content)
except SyntaxError:
etree = ET.fromstring('<null></null>')
return etree
开发者ID:pymmrd,项目名称:tuangou,代码行数:7,代码来源:base.py
示例18: validate_xml
def validate_xml(value):
value = "<div>" + value + "</div>"
try:
etree.fromstring(value)
except Exception, e:
print value
raise ValidationError("Error parsing the xml: %s" % (str(e),))
开发者ID:benliles,项目名称:django-jqmobile,代码行数:7,代码来源:validators.py
示例19: from_xml_str
def from_xml_str(xml_str, handle=None):
"""
Generates response object from the given xml string.
Args:
xml_str (str): xml string
Returns:
object (external method or managed object or generic managed object)
Example:
xml_str='''\n
<lsServer dn="org-root/ls-testsp" dynamicConPolicyName="test"\n
extIPPoolName="ext-mgmt" name="testsp" />\n
'''\n
root_element = extract_root_elem(xml_str)\n
"""
try:
xml_raw_str = ucsgenutils.add_escape_chars(xml_str)
root_elem = ET.fromstring(xml_raw_str)
except:
recovered_xml = ucsgenutils.remove_invalid_chars(xml_str)
root_elem = ET.fromstring(recovered_xml)
if root_elem.tag == "error":
error_code = root_elem.attrib['errorCode']
error_descr = root_elem.attrib['errorDescr']
raise ex.UcsException(error_code, error_descr)
class_id = ucsgenutils.word_u(root_elem.tag)
response = ucscoreutils.get_ucs_obj(class_id, root_elem)
response.from_xml(root_elem, handle)
return response
开发者ID:waghswapnil,项目名称:ucsmsdk,代码行数:34,代码来源:ucsxmlcodec.py
示例20: searchAllServers
def searchAllServers(self, query):
xml_combined = None
for server in self.servers:
root = ET.fromstring(server.getSearchXML(query))
data = ET.ElementTree(root).getchildren()
for cont in data.iter('MediaContainer'):
if xml_combined is None:
xml_combined = data
#insertion_point = xml_combined.findall("./MediaContainer")[0]
insertion_point = data
else:
insertion_point.append(cont)
for server in self.sharedServers:
data = ET.ElementTree(ET.fromstring(server.getSearchXML(query)))
for cont in data.iter('MediaContainer'):
if xml_combined is None:
xml_combined = data
#insertion_point = xml_combined.findall("./MediaContainer")[0]
insertion_point = data
else:
insertion_point.append(cont)
dprint(__name__, 0, "test: {0}", ET.tostring(xml_combined))
return ET.tostring(xml_combined)
开发者ID:nrgaway,项目名称:PlexConnect,代码行数:27,代码来源:PlexMgr.py
注:本文中的xml.etree.cElementTree.fromstring函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论