当前位置: 首页>>代码示例>>Python>>正文


Python ElementTree.ElementTree方法代码示例

本文整理汇总了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 
开发者ID:sosy-lab,项目名称:benchexec,代码行数:22,代码来源:__init__.py

示例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()) 
开发者ID:sosy-lab,项目名称:benchexec,代码行数:27,代码来源:__init__.py

示例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) 
开发者ID:YoannDupont,项目名称:SEM,代码行数:19,代码来源:document.py

示例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)) 
开发者ID:BobBuildTool,项目名称:bob,代码行数:19,代码来源:VisualStudio.py

示例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 
开发者ID:carla-simulator,项目名称:scenario_runner,代码行数:25,代码来源:route_manipulation.py

示例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") 
开发者ID:exiahuang,项目名称:SalesforceXyTools,代码行数:24,代码来源:bulk.py

示例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] 
开发者ID:google,项目名称:dspl,代码行数:25,代码来源:dspl_model_loader.py

示例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 '' 
开发者ID:google,项目名称:dspl,代码行数:18,代码来源:dspl_model_loader.py

示例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 
开发者ID:google,项目名称:dspl,代码行数:26,代码来源:dspl_model_loader.py

示例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'
    """ 
开发者ID:dxwu,项目名称:BinderFilter,代码行数:19,代码来源:test_xml_etree.py

示例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'
    """ 
开发者ID:dxwu,项目名称:BinderFilter,代码行数:27,代码来源:test_xml_etree.py

示例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 
开发者ID:su1s,项目名称:e2m3u2bouquet,代码行数:21,代码来源:e2m3u2bouquet.py

示例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 
开发者ID:tklab-tud,项目名称:ID2T,代码行数:21,代码来源:FileUtils.py

示例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) 
开发者ID:paperswithcode,项目名称:sota-extractor,代码行数:23,代码来源:parsers.py

示例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 
开发者ID:paperswithcode,项目名称:sota-extractor,代码行数:19,代码来源:parsers.py


注:本文中的xml.etree.ElementTree.ElementTree方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。