本文整理汇总了Python中xml.etree.ElementTree.fromstring方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.fromstring方法的具体用法?Python ElementTree.fromstring怎么用?Python ElementTree.fromstring使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree
的用法示例。
在下文中一共展示了ElementTree.fromstring方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: append_to
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def append_to(self, element):
branch_part = ""
if not self.is_on_master:
branch_part = ' branch="%s"' % self.__branch
material_name_part = ""
if self.__material_name is not None:
material_name_part = ' materialName="%s"' % self.__material_name
polling_part = ''
if not self.__polling:
polling_part = ' autoUpdate="false"'
destination_directory_part= ''
if self.__destination_directory:
destination_directory_part = ' dest="%s"' % self.__destination_directory
new_element = ET.fromstring(('<git url="%s"' % self.__url) + branch_part + material_name_part + polling_part + destination_directory_part + ' />')
if self.ignore_patterns:
filter_element = ET.fromstring("<filter/>")
new_element.append(filter_element)
sorted_ignore_patterns = list(self.ignore_patterns)
sorted_ignore_patterns.sort()
for ignore_pattern in sorted_ignore_patterns:
filter_element.append(ET.fromstring('<ignore pattern="%s"/>' % ignore_pattern))
element.append(new_element)
示例2: test_remove_doubletheme
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def test_remove_doubletheme(self):
context = ET.fromstring("""
<contexte xmlns="http://olst.ling.umontreal.ca/dicoenviro/">
<contexte-texte>I compare apples and oranges</contexte-texte>
<participant type="Act" role="Agent">
<fonction-syntaxique nom="Subject">
<groupe-syntaxique nom="NP">I</groupe-syntaxique>
</fonction-syntaxique>
</participant>
<lexie-att>compare</lexie-att>
<participant type="Act" role="Theme">
<fonction-syntaxique nom="Object">
<groupe-syntaxique nom="NP">apples</groupe-syntaxique>
</fonction-syntaxique>
</participant>
and
<participant type="Act" role="Theme">
<fonction-syntaxique nom="Object">
<groupe-syntaxique nom="NP">oranges</groupe-syntaxique>
</fonction-syntaxique>
</participant>
</contexte>
""")
sentence_text, frame = xmlcontext_to_frame(
"http://olst.ling.umontreal.ca/dicoenviro/", 'compare', context)
vn_frame = ET.fromstring(
"""<SYNTAX><NP value="Agent" /><VERB /><NP value="Theme" /></SYNTAX>""")
self.assertEqual(syntax_to_str(frame), syntax_to_str(vn_frame))
示例3: set_owner
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def set_owner(conn, uuid, owner):
"""Set ON_OWNER by uuid.
@param uuid: uuid of the VM
@param owner: string representing owner
"""
vmid = get_id_by_uuid(conn, uuid)
if not vmid:
return
vm = conn.lookupByID(vmid)
domain = ET.fromstring(vm.XMLDesc(0))
metadata = domain.find('./metadata') or ET.SubElement(domain, 'metadata')
owner_e = ET.SubElement(metadata, ET.QName('urn:opennode-tui', 'owner'))
owner_e.text = owner
## TODO: cleanup
open('/etc/libvirt/qemu/%s.xml' % (vm.name()), 'w').write(ET.tostring(domain))
data = open('/etc/libvirt/qemu/%s.xml' % (vm.name()), 'r').read()
domain_n = ET.fromstring(data)
owner_e = domain_n.find('./metadata/{urn:opennode-tui}owner')
assert owner_e is not None
assert owner_e.text == owner
return owner_e.text
示例4: _create_html_file
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def _create_html_file(self, sourcefile, htmlfile, errors):
name = self.generator.get_name()
root = ElementTree.fromstring(CPPCHECK_HTML_FILE)
title = root.find("head/title")
title.text = "cppcheck - report - %s" % name
body = root.find("body")
for div in body.findall("div"):
if div.get("id") == "page":
page = div
break
for div in page.findall("div"):
if div.get("id") == "header":
h1 = div.find("h1")
h1.text = "cppcheck report - %s" % name
if div.get("id") == "content":
content = div
srcnode = self.generator.bld.root.find_node(sourcefile)
hl_lines = [e["line"] for e in errors if e.has_key("line")]
formatter = CppcheckHtmlFormatter(linenos=True, style="colorful", hl_lines=hl_lines, lineanchors="line")
formatter.errors = [e for e in errors if e.has_key("line")]
css_style_defs = formatter.get_style_defs(".highlight")
lexer = pygments.lexers.guess_lexer_for_filename(sourcefile, "")
s = pygments.highlight(srcnode.read(), lexer, formatter)
table = ElementTree.fromstring(s)
content.append(table)
s = ElementTree.tostring(root, method="html")
s = CCPCHECK_HTML_TYPE + s
node = self.generator.path.get_bld().find_or_declare(htmlfile)
node.write(s)
return css_style_defs
示例5: _get_game_xml
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def _get_game_xml(self, steam_id, mode):
"""Get the XML list of games"""
fname = "games_{}.xml".format(steam_id)
if mode == "read":
log.info("Reading from {}".format(fname))
with open(fname, 'rb') as f:
content = f.read()
else:
url = self.userUrl.format(steam_id=steam_id)
log.debug("Requesting {}".format(url))
f = urlopen(url)
content = f.read()
if mode == "write":
log.info("Writing to {}".format(fname))
with open(fname, 'wb') as f:
f.write(content)
try:
root = ET.fromstring(content)
except UnicodeEncodeError:
root = ET.fromstring(content.encode('utf-8'))
return root
示例6: play
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def play(item):
logger.info("[mundonick.py] play video: " + item.url)
itemlist=[]
permalink = 'uri=mgid:uma:video:mundonick.com:' + item.url
data = scrapertools.cachePage(__urlconfig__ + permalink)
if (data == ''):
return itemlist
#logger.info(data)
import xml.etree.ElementTree as xmlet
configuration = xmlet.fromstring(data)
swfurl = configuration.find('.//player//URL').text
feedurl = configuration.find('.//player//feed').text
data = scrapertools.cachePage(feedurl)
#logger.info(data)
feed = xmlet.fromstring(data)
description = feed.find('.//item/description').text.encode("utf8","ignore").replace('<i>', '').replace('</i>', ' |').replace('<br/>', ' ').replace('LA', '');
#mediacontent = feed.find('{http://search.yahoo.com/mrss/}content').get('url')
patron = '<media:content type="text/xml" isDefault="true"\nurl="([^"]+)">'
matches = re.compile(patron,re.DOTALL).findall(data)
if DEBUG: scrapertools.printMatches(matches)
if matches: mediacontent = matches[0]
#data = scrapertools.cachePage(mediacontent)
#logger.info(data)
logger.info(description)
itemlist.append( Item(channel=__channel__, action="play", title=description, url=mediacontent, server="mundonick", thumbnail=item.thumbnail, folder=False) )
return itemlist
示例7: walk
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def walk(deps, p_node, depth, p_text):
global max_depth, w_freq
global w_connection_matrix
kids = deps.findall("./dep/governor[@idx=\""+str(p_node)+"\"]/..")
if depth > max_depth:
max_depth = depth
i = 1
for k in kids:
#ET.dump(k)
k_node = k.find("./dependent")
# ET.dump(k_node)
k_id = k_node.attrib["idx"]
# print int(p_node), int(k_id)
#w_connection_matrix[int(p_node)][int(k_id)] = 1
if k.attrib["type"] in ["ccomp", "root"]:
walk(deps, k_id, depth+1, k_node.text)
k.append(ET.fromstring("<depth>"+str(depth+1)+"</depth>"))
#elif k.attrib["type"].endswith("cl"):
# walk(deps, k_id, depth-1, k_node.text)
# k.append(ET.fromstring("<depth>"+str(depth-1)+"</depth>"))
else:
walk(deps, k_id, depth, k_node.text)
k.append(ET.fromstring("<depth>"+str(depth)+"</depth>"))
#k.append(ET.fromstring("<l_h_weight>"+str(gram_prob[p_text+" "+k.attrib["type"]])+"</l_h_weight>"))
k.append(ET.fromstring("<l_h_weight>"+cal_l_h_weight(p_text, k.attrib["type"])+"</l_h_weight>"))
k.append(ET.fromstring("<d_weight>"+str(d_weight(k_node.text))+"</d_weight>"))
i+=1
示例8: setup_github_authentication
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def setup_github_authentication():
auth_strategy = ET.fromstring('''
<authorizationStrategy class="org.jenkinsci.plugins.GithubAuthorizationStrategy">
<rootACL>
<organizationNameList class="linked-list" />
<adminUserNameList class="linked-list">
<string>mfournier</string>
<string>octo</string>
</adminUserNameList>
<authenticatedUserReadPermission>true</authenticatedUserReadPermission>
<useRepositoryPermissions>false</useRepositoryPermissions>
<authenticatedUserCreateJobPermission>false</authenticatedUserCreateJobPermission>
<allowGithubWebHookPermission>true</allowGithubWebHookPermission>
<allowCcTrayPermission>true</allowCcTrayPermission>
<allowAnonymousReadPermission>true</allowAnonymousReadPermission>
</rootACL>
</authorizationStrategy>
''')
security_realm = ET.fromstring('''
<securityRealm class="org.jenkinsci.plugins.GithubSecurityRealm">
<githubWebUri>https://github.com</githubWebUri>
<githubApiUri>https://api.github.com</githubApiUri>
<clientID />
<clientSecret />
</securityRealm>
''')
root.find('useSecurity').text = 'true'
root.remove(root.find('authorizationStrategy'))
root.append(auth_strategy)
root.remove(root.find('securityRealm'))
root.append(security_realm)
root.find('securityRealm').find('clientID').text = vars['github_clientid']
root.find('securityRealm').find('clientSecret').text = vars['github_clientsecret']
示例9: _create_html_file
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def _create_html_file(self, sourcefile, htmlfile, errors):
name = self.generator.get_name()
root = ElementTree.fromstring(CPPCHECK_HTML_FILE)
title = root.find('head/title')
title.text = 'cppcheck - report - %s' % name
body = root.find('body')
for div in body.findall('div'):
if div.get('id') == 'page':
page = div
break
for div in page.findall('div'):
if div.get('id') == 'header':
h1 = div.find('h1')
h1.text = 'cppcheck report - %s' % name
if div.get('id') == 'content':
content = div
srcnode = self.generator.bld.root.find_node(sourcefile)
hl_lines = [e['line'] for e in errors if e.has_key('line')]
formatter = CppcheckHtmlFormatter(linenos=True, style='colorful', hl_lines=hl_lines, lineanchors='line')
formatter.errors = [e for e in errors if e.has_key('line')]
css_style_defs = formatter.get_style_defs('.highlight')
lexer = pygments.lexers.guess_lexer_for_filename(sourcefile, "")
s = pygments.highlight(srcnode.read(), lexer, formatter)
table = ElementTree.fromstring(s)
content.append(table)
s = ElementTree.tostring(root, method='html')
s = CCPCHECK_HTML_TYPE + s
node = self.generator.path.get_bld().find_or_declare(htmlfile)
node.write(s)
return css_style_defs
示例10: mine_disease_to_nct
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def mine_disease_to_nct(ldisease, fout=None, ctmin=100):
url = 'http://clinicaltrials.gov/search?cond=%s&displayxml=true&count=%s'
log.info('found %d disease to process \n' % len(ldisease))
ldisease = sorted(map(lambda x: ' '.join(x.lower().split()), ldisease))
nct_disease = defaultdict(list)
c = 1
for d in sorted(ldisease):
log.info('processing: "%s"' % d)
d = d.replace(',', '')
fd = d.replace(' ', '+')
# number of trials
xmltree = xml_parser.fromstring(download_web_data(url % (fd, '0')))
nres = xmltree.get('count')
try:
if int(nres) < ctmin:
log.info(' --- found only %s trials - skipping \n' % nres)
continue
except Exception as e:
log.error(e)
continue
# list of trials
xmltree = xml_parser.fromstring(download_web_data(url % (fd, nres)))
lnct = xmltree.findall('clinical_study')
# nct = set()
for ct in lnct:
try:
cod = ct.find('nct_id')
# nct.add(cod.text)
nct_disease[cod.text].append(d)
except Exception as e:
log.error(e)
return nct_disease
示例11: _process_case_block
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
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
示例12: test_make_xml
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def test_make_xml(self):
hostname, servicename, instruction = 'MixedCase', 'Mixed Case', '/cpu/count'
check = ncpacheck.NCPACheck(self.config, instruction, hostname, servicename)
xml = nrdp.make_xml(check).toxml()
tree = ET.fromstring(xml)
servicename = tree.findall('servicename')[0]
hostname = tree.findall('hostname')[0]
stdout = tree.findall('output')[0]
state = tree.findall('state')[0]
self.assertEquals(tree.tag, 'checkresult')
self.assertEquals(tree.attrib, {'type': 'service'})
self.assertEquals(servicename.text, 'Mixed Case')
self.assertEquals(hostname.text, 'MixedCase')
self.assertIsNotNone(stdout)
self.assertIsNotNone(state)
hostname, servicename, instruction = 'testing_host', '__HOST__', '/cpu/count'
check = ncpacheck.NCPACheck(self.config, instruction, hostname, servicename)
xml = nrdp.make_xml(check).toxml()
tree = ET.fromstring(xml)
hostname = tree.findall('hostname')[0]
stdout = tree.findall('output')[0]
state = tree.findall('state')[0]
self.assertEquals(tree.tag, 'checkresult')
self.assertEquals(tree.attrib, {'type': 'host'})
self.assertEquals(tree.findall('servicename'), [])
self.assertEquals(hostname.text, 'testing_host')
self.assertIsNotNone(stdout)
self.assertIsNotNone(state)
示例13: listen
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def listen(self):
while True:
data = self.recv_XML()
tag = data[1:data.find(" ")]
if tag == "u": #User joined
user_data = ET.fromstring(data).attrib
# Sometimes users re-login without properly logging out (e.g.
# when their rank is changed), so we don't want to have any
# duplicates.
self.users.remove(user_data["u"])
self.users.append(user_data)
print(self.users)
if tag == "l": #User left
user_id = ET.fromstring(data).attrib["u"]
self.users.remove(id)
print(self.users)
if tag == "m": #User spoke
content = ET.fromstring(data).attrib
user_id = content["u"]
user_message = content["t"]
if is_foul(user_message):
self.kick(user_id, "Offensive language")
elif user_message[0] == "!":
self.parse_command(user_message, user_id)
if tag == "logout":
return
示例14: test_get_banks_details_not_found
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def test_get_banks_details_not_found(self, mock_get):
with self.app as c:
with c.session_transaction() as session:
session["application_type"] = "cancel"
session["images"] = ["/document/1/image/1"]
session["original_image_data"] = ["/document/1/image/1"]
response = self.app.post("/get_details", data={"reg_no": "50001"})
html = response.data.decode("utf-8")
tree = ET.fromstring(html)
assert tree.find('.//*[@id="class_data"]/h4').text == "Retrieve original details"
assert tree.find('.//*[@id="class_data"]/p/strong').text == "Registration not found please re-enter"
# Check Rectify leg
with self.app as c:
with c.session_transaction() as session:
session["application_type"] = "rectify"
session["images"] = ["/document/1/image/1"]
session["original_image_data"] = ["/document/1/image/1"]
response = self.app.post("/get_details", data={"reg_no": "50001"})
html = response.data.decode("utf-8")
tree = ET.fromstring(html)
assert tree.find('.//*[@id="main"]/div[2]/div/h4').text == "Bankruptcy Rectification"
assert tree.find('.//*[@id="class_data"]/p/strong').text == "Registration not found please re-enter"
示例15: _parse_log
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def _parse_log(self, log):
"""
Parse the "log" section produced by BoostTest.
This is always a XML file, and from this we produce most of the
failures possible when running BoostTest.
"""
# Fatal errors apparently generate invalid xml in the form:
# <FatalError>...</FatalError><TestLog>...</TestLog>
# so we have to manually split it into two xmls if that's the case.
parsed_elements = []
if log.startswith('<FatalError'):
fatal, log = log.split('</FatalError>')
fatal += '</FatalError>' # put it back, removed by split()
fatal_root = ElementTree.fromstring(fatal)
fatal_root.text = 'Fatal Error: %s' % fatal_root.text
parsed_elements.append(fatal_root)
log_root = ElementTree.fromstring(log)
parsed_elements.extend(log_root.findall('Exception'))
parsed_elements.extend(log_root.findall('Error'))
parsed_elements.extend(log_root.findall('FatalError'))
result = []
for elem in parsed_elements:
filename = elem.attrib['file']
linenum = int(elem.attrib['line'])
result.append(BoostTestFailure(filename, linenum, elem.text))
return result