本文整理汇总了Python中xml.etree.ElementTree.ElementTree方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.ElementTree方法的具体用法?Python ElementTree.ElementTree怎么用?Python ElementTree.ElementTree使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree
的用法示例。
在下文中一共展示了ElementTree.ElementTree方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse_table_definition_file
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ElementTree [as 别名]
def parse_table_definition_file(file):
"""
Read an parse the XML of a table-definition file.
@return: an ElementTree object for the table definition
"""
logging.info("Reading table definition from '%s'...", file)
if not os.path.isfile(file):
handle_error("File '%s' does not exist.", file)
try:
tableGenFile = ElementTree.ElementTree().parse(file)
except OSError as e:
handle_error("Could not read result file %s: %s", file, e)
except ElementTree.ParseError as e:
handle_error("Table file %s is invalid: %s", file, e)
if "table" != tableGenFile.tag:
handle_error(
"Table file %s is invalid: It's root element is not named 'table'.", file
)
return tableGenFile
示例2: test_description
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ElementTree [as 别名]
def test_description(self):
test_description = """
äöüß This tests non-ASCII characters, line breaks, whitespace, and
<>&"' XML special characters.
"""
with tempfile.NamedTemporaryFile(
prefix="description", suffix=".txt", dir=self.tmp, mode="w+"
) as desc:
desc.write(test_description)
desc.flush()
self.run_cmd(
self.benchmark_test_file,
"--no-compress-results",
"--description-file",
desc.name,
)
generated_files = glob.glob(os.path.join(self.output_dir, "*.xml"))
assert generated_files, "error in test, no results generated"
for f in generated_files:
result_xml = ElementTree.ElementTree().parse(f)
actual_description = result_xml.find("description").text
self.assertEqual(actual_description, test_description.strip())
示例3: from_xml
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ElementTree [as 别名]
def from_xml(cls, xml, chunks_to_load=None, load_subtypes=True, type_separator=u"."):
if sem.misc.is_string(xml):
data = ET.parse(xml)
elif isinstance(xml, ET.ElementTree):
data = xml
elif isinstance(xml, type(ET.Element("a"))): # did not ind a better way to do this
data = xml
else:
raise TypeError("Invalid type for loading XML-SEM document: {0}".format(type(xml)))
root = data.getroot()
if root.tag != "sem":
raise ValueError("Not sem xml file type: '{0}'".format(root.tag))
doc_list = []
for document in list(root):
doc_list.append(Document.from_xml(document))
return SEMCorpus(doc_list)
示例4: generateUser
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ElementTree [as 别名]
def generateUser(self):
groups = []
if self.runTargets:
# VS can handle only one target per project
target = self.runTargets[0]
g = ElementTree.Element("PropertyGroup", {"Condition" : "'$(Configuration)|$(Platform)'=='Build|Win32'"})
ElementTree.SubElement(g, "LocalDebuggerCommand").text = str(target)
ElementTree.SubElement(g, "DebuggerFlavor").text = "WindowsLocalDebugger"
groups.append(ElementTree.tostring(g, encoding="unicode"))
n = ElementTree.Element("PropertyGroup", {"Condition" : "'$(Configuration)|$(Platform)'=='Checkout+Build|Win32'"})
ElementTree.SubElement(g, "LocalDebuggerCommand").text = str(target)
ElementTree.SubElement(g, "DebuggerFlavor").text = "WindowsLocalDebugger"
groups.append(ElementTree.tostring(g, encoding="unicode"))
# FIXME: print warning when more than one taget exists
return USER_TEMPLATE.format(GROUPS="\n".join(groups))
示例5: _get_latlon_ref
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ElementTree [as 别名]
def _get_latlon_ref(world):
"""
Convert from waypoints world coordinates to CARLA GPS coordinates
:return: tuple with lat and lon coordinates
"""
xodr = world.get_map().to_opendrive()
tree = ET.ElementTree(ET.fromstring(xodr))
# default reference
lat_ref = 42.0
lon_ref = 2.0
for opendrive in tree.iter("OpenDRIVE"):
for header in opendrive.iter("header"):
for georef in header.iter("geoReference"):
if georef.text:
str_list = georef.text.split(' ')
for item in str_list:
if '+lat_0' in item:
lat_ref = float(item.split('=')[1])
if '+lon_0' in item:
lon_ref = float(item.split('=')[1])
return lat_ref, lon_ref
示例6: create_job_doc
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ElementTree [as 别名]
def create_job_doc(self, object_name=None, operation=None,
contentType='CSV', concurrency=None, external_id_name=None):
root = ET.Element("jobInfo")
root.set("xmlns", self.jobNS)
op = ET.SubElement(root, "operation")
op.text = operation
obj = ET.SubElement(root, "object")
obj.text = object_name
if external_id_name:
ext = ET.SubElement(root, 'externalIdFieldName')
ext.text = external_id_name
if concurrency:
con = ET.SubElement(root, "concurrencyMode")
con.text = concurrency
ct = ET.SubElement(root, "contentType")
ct.text = contentType
buf = BytesIO()
tree = ET.ElementTree(root)
tree.write(buf, encoding="UTF-8")
return buf.getvalue().decode("utf-8")
示例7: _NSParser
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ElementTree [as 别名]
def _NSParser(input_file):
"""A special ElementTree parser that gets all the imported namespaces.
Args:
input_file: A file-like object containing XML
Returns:
A list with two elements: the root of the ElementTree, and a list of
namespace strings imported by the XML file.
"""
events = ('start', 'start-ns')
root = None
namespace_list = []
for event, element in xml.etree.ElementTree.iterparse(input_file, events):
if event == 'start-ns':
namespace_list.append(element)
elif event == 'start':
if root is None:
root = element
return [xml.etree.ElementTree.ElementTree(root), namespace_list]
示例8: _GetValue
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ElementTree [as 别名]
def _GetValue(parent_element):
"""Get the text nested inside an XML element's value element.
Args:
parent_element: An ElementTree element
Returns:
String inside value tag inside parent or, if no such tag can be found, None
"""
if parent_element is not None:
value_element = parent_element.find(_DSPL_SCHEMA_PREFIX + 'value')
if value_element is not None:
return value_element.text
return ''
示例9: ElementsToAttributes
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ElementTree [as 别名]
def ElementsToAttributes(concept_element):
"""Process the attributes in an an ElementTree concept element.
Args:
concept_element: An ElementTree concept element
Returns:
A list of dspl_model.Attribute instances, populated with the data from the
argument concept element.
"""
attribute_elements = concept_element.findall(
_DSPL_SCHEMA_PREFIX + 'attribute')
dspl_attributes = []
for attribute_element in attribute_elements:
attribute_concept = attribute_element.get('concept')
# For now, only handle attributes with a concept reference
if attribute_concept:
dspl_attributes.append(
dspl_model.Attribute(attribute_concept, _GetValue(attribute_element)))
return dspl_attributes
示例10: file_init
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ElementTree [as 别名]
def file_init():
"""
>>> import StringIO
>>> stringfile = StringIO.StringIO(SAMPLE_XML)
>>> tree = ET.ElementTree(file=stringfile)
>>> tree.find("tag").tag
'tag'
>>> tree.find("section/tag").tag
'tag'
>>> tree = ET.ElementTree(file=SIMPLE_XMLFILE)
>>> tree.find("element").tag
'element'
>>> tree.find("element/../empty-element").tag
'empty-element'
"""
示例11: parseliteral
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ElementTree [as 别名]
def parseliteral():
"""
>>> element = ET.XML("<html><body>text</body></html>")
>>> ET.ElementTree(element).write(sys.stdout)
<html><body>text</body></html>
>>> element = ET.fromstring("<html><body>text</body></html>")
>>> ET.ElementTree(element).write(sys.stdout)
<html><body>text</body></html>
>>> sequence = ["<html><body>", "text</bo", "dy></html>"]
>>> element = ET.fromstringlist(sequence)
>>> print ET.tostring(element)
<html><body>text</body></html>
>>> print "".join(ET.tostringlist(element))
<html><body>text</body></html>
>>> ET.tostring(element, "ascii")
"<?xml version='1.0' encoding='ascii'?>\\n<html><body>text</body></html>"
>>> _, ids = ET.XMLID("<html><body>text</body></html>")
>>> len(ids)
0
>>> _, ids = ET.XMLID("<html><body id='body'>text</body></html>")
>>> len(ids)
1
>>> ids["body"].tag
'body'
"""
示例12: parse_map_xmltvsources_xml
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ElementTree [as 别名]
def parse_map_xmltvsources_xml(self):
"""Check for a mapping override file and parses it if found
"""
self._xmltv_sources_list = {}
mapping_file = self._get_mapping_file()
if mapping_file:
try:
tree = ET.ElementTree(file=mapping_file)
for group in tree.findall('.//xmltvextrasources/group'):
group_name = group.attrib.get('id')
urllist = []
for url in group:
urllist.append(url.text)
self._xmltv_sources_list[group_name] = urllist
except Exception, e:
msg = 'Corrupt override.xml file'
print(msg)
if DEBUG:
raise msg
示例13: parse_xml
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ElementTree [as 别名]
def parse_xml(filepath: str):
"""
Parses an XML File
It is assumed, that packets are placed on the second hierarchical level and packet-information is encoded
as attributes
:param filepath: the path to the XML file to be parsed
:return: a List of Dictionaries, each Dictionary contains the information of one packet
"""
tree = ElementTree.parse(filepath)
root = tree.getroot()
# Convert Tree to List of Dictionaries
packets = []
for child in root:
packets.append(child.attrib)
return packets
示例14: _unwind
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ElementTree [as 别名]
def _unwind(cls, el: ElementTree, keep_links) -> "Text":
start = el.text or ""
if el.tag == "a":
links = [Link(title=el.text, url=el.attrib.get("href", None))]
else:
links = []
children = ""
for child in el:
t = cls._unwind(child, keep_links=keep_links)
children += t.text
links.extend(t.links)
end = el.tail or ""
if el.tag == "a" and keep_links:
return cls(
text=f"[{start}]({el.attrib.get('href', '')}){children}{end}",
links=links,
)
return cls(text=start + children + end, links=links)
示例15: parse_subdatasets
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import ElementTree [as 别名]
def parse_subdatasets(
parent: Dataset, pairs: List[Tuple[ElementTree, ElementTree]]
) -> List[Dataset]:
subdatasets = []
for p, table in pairs:
strong = p.find("strong")
if strong is None:
continue
subdatasets.append(
Dataset(
name=strong.text.strip().strip(":"),
is_subdataset=True,
parent=parent,
sota=parse_sota(table),
)
)
return subdatasets