如何使用ElementTree以递归方式迭代Python中的XML标签?

klo*_*oop 15 python xml

我试图使用ElementTree迭代树中的所有节点.

我做的事情如下:

  tree = ET.parse("/tmp/test.xml")

  root = tree.getroot()

  for child in root:
       ### do something with child
Run Code Online (Sandbox Code Playgroud)

问题是child是一个Element对象而不是ElementTree对象,所以我无法进一步查看它并递归迭代它的元素.有没有办法在"root"上进行不同的迭代,以便迭代树中的顶级节点(直接子节点)并返回与root本身相同的类?

Rob*_*tie 27

要迭代所有节点,请在ElementTree上使用iter方法,而不是根元素.

根是一个元素,就像树中的其他元素一样,只有真正具有自己的属性和子元素的上下文.ElementTree具有所有元素的上下文.

例如,给定这个xml

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
Run Code Online (Sandbox Code Playgroud)

您可以执行以下操作

>>> import xml.etree.ElementTree as ET
>>> tree = ET.parse('test.xml')
>>> for elem in tree.iter():
...     print elem
... 
<Element 'data' at 0x10b2d7b50>
<Element 'country' at 0x10b2d7b90>
<Element 'rank' at 0x10b2d7bd0>
<Element 'year' at 0x10b2d7c50>
<Element 'gdppc' at 0x10b2d7d10>
<Element 'neighbor' at 0x10b2d7e90>
<Element 'neighbor' at 0x10b2d7ed0>
<Element 'country' at 0x10b2d7f10>
<Element 'rank' at 0x10b2d7f50>
<Element 'year' at 0x10b2d7f90>
<Element 'gdppc' at 0x10b2d7fd0>
<Element 'neighbor' at 0x10b2db050>
<Element 'country' at 0x10b2db090>
<Element 'rank' at 0x10b2db0d0>
<Element 'year' at 0x10b2db110>
<Element 'gdppc' at 0x10b2db150>
<Element 'neighbor' at 0x10b2db190>
<Element 'neighbor' at 0x10b2db1d0>
Run Code Online (Sandbox Code Playgroud)

  • 您还如何打印这些值? (2认同)
  • 是否可以使用fromstring()而不是parse()来做到这一点?前者直接给您根元素 (2认同)

ssj*_*don 9

添加到Robert Christie的答案中,可以fromstring()通过将Element转换为ElementTree 来迭代所有节点:

import xml.etree.ElementTree as ET

e = ET.ElementTree(ET.fromstring(xml_string))
for elt in e.iter():
    print "%s: '%s'" % (elt.tag, elt.text)
Run Code Online (Sandbox Code Playgroud)


tru*_*ory 7

你也可以访问这样的特定元素:

country= tree.findall('.//country')
Run Code Online (Sandbox Code Playgroud)

然后循环range(len(country)) 并访问

  • 这完美地工作。它是一个新功能吗?我想知道为什么没有人提到它。它是如何工作的?(在搜索 `.//` 时遇到问题) (2认同)

Fat*_*ici 7

除了罗伯特克里斯蒂接受的答案之外,单独打印值和标签非常容易:

tree = ET.parse('test.xml')
for elem in tree.iter():
    print(elem.tag, elem.text)
Run Code Online (Sandbox Code Playgroud)