如何在python中从Elementtree获取孙子元素

时间:2013-06-25 09:48:05

标签: python elementtree

假设我有一个像这样的XML代码:

<root>
    <a>
        <b>
           ....
        </b>
        <c>
           ....
        </c>
        <d>
           ....
        </d>
    </a>
    <d><c></c><a></a></d>
</root>

是否有一个函数可以将孙子元素赋予某个子节点? 例如,在上面的XML代码中,如果我传递'd',我希望它返回'c'和'a'。

我尝试了getChildren(),但我想这会返回属性,但不会返回子元素。我甚至没有属性btw。

谢谢。

3 个答案:

答案 0 :(得分:2)

根元素是可迭代的:

>>> import xml.etree.ElementTree as ET
>>> xml = "<root><a><b>....</b><c>....</c><d>....</d></a><d><c><a></a></c></d></root>"
>>> root = ET.fromstring(xml)
>>> root
<Element 'root' at 0x7fa86a7ea610>
>>> for child in root:
...     print child
... 
<Element 'a' at 0x7fa86a7ea650>
<Element 'd' at 0x7fa86a7ea810>

获取特定的孙子元素:

>>> root = ET.fromstring(xml)
>>> root.find("d").getchildren()
[<Element 'c' at 0x7fce44939650>, <Element 'a' at 0x7fce44939690>]

如果你想要标签而不是ElementTree对象:

>>> [e.tag for e in  root.find("d").getchildren()]
['c', 'a']

请注意,<Element 'c' at 0x7fce44939650>代表ElementTree Element对象(与root相同),其API定义为in the docs

答案 1 :(得分:0)

鉴于root是树的根:

>>> [grchild for child in root for grchild in child]
[<Element 'b' at 0xb6cbad4c>, <Element 'c' at 0xb6cbaedc>,
<Element 'd' at 0xb6cbad24>, <Element 'c' at 0xb6cbaaa4>]

好的,让我们用Haskell的方式写一个递归函数:

def recurse(node):
    for child in node:
        print(child)
        recurse(child)

>>> node = root.find('d')
>>> recurse(node)
<Element 'c' at 0xb6cbaaa4>
<Element 'a' at 0xb6cbac0c>

答案 2 :(得分:0)

假设您已经解析了文档,[i.getchildren() for i in root.findall('d')]可能就是您想要的!

为了更通用,你可以有一个功能


def getGrandChildOfTag(tagName, root):
    return [i.getchildren() for i in root.findall(tagName)]

相关问题