本文整理汇总了Python中elementtree.ElementTree.fromstring方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.fromstring方法的具体用法?Python ElementTree.fromstring怎么用?Python ElementTree.fromstring使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类elementtree.ElementTree
的用法示例。
在下文中一共展示了ElementTree.fromstring方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: retrieve_styles
# 需要导入模块: from elementtree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree import fromstring [as 别名]
def retrieve_styles(self, extension):
"""Retrieve the stylesheet from either a .xml file or from
a .odt (zip) file. Return the content as a string.
"""
s2 = None
stylespath = self.settings.stylesheet
ext = os.path.splitext(stylespath)[1]
if ext == '.xml':
stylesfile = open(stylespath, 'r')
s1 = stylesfile.read()
stylesfile.close()
elif ext == extension:
zfile = zipfile.ZipFile(stylespath, 'r')
s1 = zfile.read('styles.xml')
s2 = zfile.read('content.xml')
zfile.close()
else:
raise RuntimeError('stylesheet path (%s) must be %s or .xml file' %(stylespath, extension))
self.str_stylesheet = s1
self.str_stylesheetcontent = s2
self.dom_stylesheet = etree.fromstring(self.str_stylesheet)
self.dom_stylesheetcontent = etree.fromstring(self.str_stylesheetcontent)
self.table_styles = self.extract_table_styles(s2)
示例2: visit_raw
# 需要导入模块: from elementtree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree import fromstring [as 别名]
def visit_raw(self, node):
if 'format' in node.attributes:
formats = node.attributes['format']
formatlist = formats.split()
if 'odt' in formatlist:
rawstr = node.astext()
attrstr = ' '.join(['%s="%s"' % (k, v, )
for k,v in list(CONTENT_NAMESPACE_ATTRIB.items())])
contentstr = '<stuff %s>%s</stuff>' % (attrstr, rawstr, )
if WhichElementTree != "lxml":
contentstr = contentstr.encode("utf-8")
content = etree.fromstring(contentstr)
elements = content.getchildren()
if len(elements) > 0:
el1 = elements[0]
if self.in_header:
pass
elif self.in_footer:
pass
else:
self.current_element.append(el1)
raise nodes.SkipChildren()
示例3: retrieve_styles
# 需要导入模块: from elementtree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree import fromstring [as 别名]
def retrieve_styles(self, extension):
"""Retrieve the stylesheet from either a .xml file or from
a .odt (zip) file. Return the content as a string.
"""
s2 = None
stylespath = self.settings.stylesheet
ext = os.path.splitext(stylespath)[1]
if ext == '.xml':
stylesfile = open(stylespath, 'r')
s1 = stylesfile.read()
stylesfile.close()
elif ext == extension:
zfile = zipfile.ZipFile(stylespath, 'r')
s1 = zfile.read('styles.xml')
s2 = zfile.read('content.xml')
zfile.close()
else:
raise RuntimeError, 'stylesheet path (%s) must be %s or .xml file' %(stylespath, extension)
self.str_stylesheet = s1
self.str_stylesheetcontent = s2
self.dom_stylesheet = etree.fromstring(self.str_stylesheet)
self.dom_stylesheetcontent = etree.fromstring(self.str_stylesheetcontent)
self.table_styles = self.extract_table_styles(s2)
示例4: visit_raw
# 需要导入模块: from elementtree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree import fromstring [as 别名]
def visit_raw(self, node):
if 'format' in node.attributes:
formats = node.attributes['format']
formatlist = formats.split()
if 'odt' in formatlist:
rawstr = node.astext()
attrstr = ' '.join(['%s="%s"' % (k, v, )
for k,v in CONTENT_NAMESPACE_ATTRIB.items()])
contentstr = '<stuff %s>%s</stuff>' % (attrstr, rawstr, )
if WhichElementTree != "lxml":
contentstr = contentstr.encode("utf-8")
content = etree.fromstring(contentstr)
elements = content.getchildren()
if len(elements) > 0:
el1 = elements[0]
if self.in_header:
pass
elif self.in_footer:
pass
else:
self.current_element.append(el1)
raise nodes.SkipChildren()
示例5: from_xml
# 需要导入模块: from elementtree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree import fromstring [as 别名]
def from_xml(self, element=None, data_record=None):
if data_record is not None:
self.root = ET.fromstring(data_record)
elif element is not None:
self.root = element
if self.root is not None:
if self.root.tag != SDX_SUNSPEC_DATA:
raise SunSpecDataError("Unexpected root element: %s" % (self.root.tag))
self.version = self.root.attrib.get(SDX_SUNSPEC_DATA_VERSION)
for d in self.root.findall('*'):
if d.tag != SDX_DEVICE:
raise SunSpecDataError("Unexpected '{}' element in '{}' element".format(d.tag, self.root.tag))
dd = DeviceData()
dd.from_xml(d)
self.device_data.append(dd)
示例6: test_modbus_mbmap_to_xml
# 需要导入模块: from elementtree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree import fromstring [as 别名]
def test_modbus_mbmap_to_xml(self):
filename = os.path.join(self.pathlist.path[1], 'mbmap_test_device_1.xml')
f = open(filename, 'r')
map_data = f.read()
f.close()
root = ET.fromstring(map_data)
expected_output_filename = os.path.join(self.pathlist.path[1], 'mbmap_test_device_1_processed.xml')
f = open(expected_output_filename, 'r')
expected_output = f.read()
f.close()
expected_root = ET.fromstring(expected_output)
# Convert from xml to ModbusMap and back to xml to verify to_xml() is working properly
m1 = mbmap.ModbusMap()
m1.from_xml(element=root)
assert m1.to_xml().find('regs').text == expected_root.find('regs').text
示例7: _le_xml
# 需要导入模块: from elementtree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree import fromstring [as 别名]
def _le_xml(self, arquivo):
if arquivo is None:
return False
if not isinstance(arquivo, basestring):
arquivo = etree.tounicode(arquivo)
if arquivo is not None:
if isinstance(arquivo, basestring):
if NAMESPACE_NFSE in arquivo:
arquivo = por_acentos(arquivo)
if u'<' in arquivo:
self._xml = etree.fromstring(tira_abertura(arquivo))
else:
arq = open(arquivo)
txt = ''.join(arq.readlines())
txt = tira_abertura(txt)
arq.close()
self._xml = etree.fromstring(txt)
else:
self._xml = etree.parse(arquivo)
return True
return False
示例8: validar
# 需要导入模块: from elementtree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree import fromstring [as 别名]
def validar(self):
arquivo_esquema = self.caminho_esquema + self.arquivo_esquema
# Aqui é importante remover a declaração do encoding
# para evitar erros de conversão unicode para ascii
xml = tira_abertura(self.xml).encode(u'utf-8')
esquema = etree.XMLSchema(etree.parse(arquivo_esquema))
if not esquema.validate(etree.fromstring(xml)):
for e in esquema.error_log:
if e.level == 1:
self.alertas.append(e.message.replace('{http://www.portalfiscal.inf.br/nfe}', ''))
elif e.level == 2:
self.erros.append(e.message.replace('{http://www.portalfiscal.inf.br/nfe}', ''))
return esquema.error_log
示例9: parseliteral
# 需要导入模块: from elementtree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree import fromstring [as 别名]
def parseliteral():
r"""
>>> element = ElementTree.XML("<html><body>text</body></html>")
>>> ElementTree.ElementTree(element).write(sys.stdout)
<html><body>text</body></html>
>>> element = ElementTree.fromstring("<html><body>text</body></html>")
>>> ElementTree.ElementTree(element).write(sys.stdout)
<html><body>text</body></html>
>>> print ElementTree.tostring(element)
<html><body>text</body></html>
>>> print ElementTree.tostring(element, "ascii")
<?xml version='1.0' encoding='ascii'?>
<html><body>text</body></html>
>>> _, ids = ElementTree.XMLID("<html><body>text</body></html>")
>>> len(ids)
0
>>> _, ids = ElementTree.XMLID("<html><body id='body'>text</body></html>")
>>> len(ids)
1
>>> ids["body"].tag
'body'
"""
示例10: CreateClassFromXMLString
# 需要导入模块: from elementtree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree import fromstring [as 别名]
def CreateClassFromXMLString(target_class, xml_string, string_encoding=None):
"""Creates an instance of the target class from the string contents.
Args:
target_class: class The class which will be instantiated and populated
with the contents of the XML. This class must have a _tag and a
_namespace class variable.
xml_string: str A string which contains valid XML. The root element
of the XML string should match the tag and namespace of the desired
class.
string_encoding: str The character encoding which the xml_string should
be converted to before it is interpreted and translated into
objects. The default is None in which case the string encoding
is not changed.
Returns:
An instance of the target class with members assigned according to the
contents of the XML - or None if the root XML tag and namespace did not
match those of the target class.
"""
encoding = string_encoding or XML_STRING_ENCODING
if encoding and isinstance(xml_string, str):
xml_string = xml_string.encode(encoding)
tree = ElementTree.fromstring(xml_string)
return _CreateClassFromElementTree(target_class, tree)
示例11: parse
# 需要导入模块: from elementtree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree import fromstring [as 别名]
def parse(xml_string, target_class=None, version=1, encoding=None):
"""Parses the XML string according to the rules for the target_class.
Args:
xml_string: str or unicode
target_class: XmlElement or a subclass. If None is specified, the
XmlElement class is used.
version: int (optional) The version of the schema which should be used when
converting the XML into an object. The default is 1.
encoding: str (optional) The character encoding of the bytes in the
xml_string. Default is 'UTF-8'.
"""
if target_class is None:
target_class = XmlElement
if isinstance(xml_string, str):
if encoding is None:
xml_string = xml_string.encode(STRING_ENCODING)
else:
xml_string = xml_string.encode(encoding)
tree = ElementTree.fromstring(xml_string)
return _xml_element_from_tree(tree, target_class, version)
示例12: CreateClassFromXMLString
# 需要导入模块: from elementtree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree import fromstring [as 别名]
def CreateClassFromXMLString(target_class, xml_string, string_encoding=None):
"""Creates an instance of the target class from the string contents.
Args:
target_class: class The class which will be instantiated and populated
with the contents of the XML. This class must have a _tag and a
_namespace class variable.
xml_string: str A string which contains valid XML. The root element
of the XML string should match the tag and namespace of the desired
class.
string_encoding: str The character encoding which the xml_string should
be converted to before it is interpreted and translated into
objects. The default is None in which case the string encoding
is not changed.
Returns:
An instance of the target class with members assigned according to the
contents of the XML - or None if the root XML tag and namespace did not
match those of the target class.
"""
encoding = string_encoding or XML_STRING_ENCODING
if encoding and isinstance(xml_string, unicode):
xml_string = xml_string.encode(encoding)
tree = ElementTree.fromstring(xml_string)
return _CreateClassFromElementTree(target_class, tree)
示例13: testSchemaParsePreservesMarkup
# 需要导入模块: from elementtree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree import fromstring [as 别名]
def testSchemaParsePreservesMarkup(self):
outer = atom.core.xml_element_from_string(SAMPLE_XML, Outer)
tree1 = ElementTree.fromstring(SAMPLE_XML)
tree2 = ElementTree.fromstring(outer.to_string())
self.assert_trees_similar(tree1, tree2)
found_x_and_y = False
found_x_123 = False
child = tree1.find('{http://example.com/xml/1}inner')
matching_children = tree2.findall(child.tag)
for match in matching_children:
if 'y' in match.attrib and match.attrib['y'] == 'abc':
if match.attrib['x'] == '234':
found_x_and_y = True
self.assert_(match.attrib['x'] == '234')
if 'x' in match.attrib and match.attrib['x'] == '123':
self.assert_('y' not in match.attrib)
found_x_123 = True
self.assert_(found_x_and_y)
self.assert_(found_x_123)
示例14: parse
# 需要导入模块: from elementtree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree import fromstring [as 别名]
def parse(xml_string, target_class=None, version=1, encoding=None):
"""Parses the XML string according to the rules for the target_class.
Args:
xml_string: str or unicode
target_class: XmlElement or a subclass. If None is specified, the
XmlElement class is used.
version: int (optional) The version of the schema which should be used when
converting the XML into an object. The default is 1.
encoding: str (optional) The character encoding of the bytes in the
xml_string. Default is 'UTF-8'.
"""
if target_class is None:
target_class = XmlElement
if isinstance(xml_string, unicode):
if encoding is None:
xml_string = xml_string.encode(STRING_ENCODING)
else:
xml_string = xml_string.encode(encoding)
tree = ElementTree.fromstring(xml_string)
return _xml_element_from_tree(tree, target_class, version)
示例15: get_proxy_ticket
# 需要导入模块: from elementtree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree import fromstring [as 别名]
def get_proxy_ticket(self, pgt):
"""Returns proxy ticket given the proxy granting ticket"""
response = urllib_request.urlopen(self.get_proxy_url(pgt))
if response.code == 200:
from lxml import etree
root = etree.fromstring(response.read())
tickets = root.xpath(
"//cas:proxyTicket",
namespaces={"cas": "http://www.yale.edu/tp/cas"}
)
if len(tickets) == 1:
return tickets[0].text
errors = root.xpath(
"//cas:authenticationFailure",
namespaces={"cas": "http://www.yale.edu/tp/cas"}
)
if len(errors) == 1:
raise CASError(errors[0].attrib['code'], errors[0].text)
raise CASError("Bad http code %s" % response.code)