如何在Python中从Elementtree获取孙子元素 [英] How to get grandchild elements from Elementtree in python
问题描述
说我有一个像这样的XML代码:
Say I have an XML code like this one:
<root>
<a>
<b>
....
</b>
<c>
....
</c>
<d>
....
</d>
</a>
<d><c></c><a></a></d>
</root>
是否有一个函数可以在给定特定子节点的情况下获取孙子元素?
Foe示例,在上面的XML代码中,如果我传递'd',我希望它返回'c'和'a'。
Is there a function to get the grandchildren elements given a certain child node? Foe example, in the XML code above, if I pass 'd', I would like it to return 'c' and 'a'.
I尝试过getChildren(),但我猜这返回属性,但不返回children元素。我什至没有属性。
I tried getChildren(), but I guess this returns attributes, but not the children elements. I don't even have attributes btw.
谢谢。
推荐答案
根元素是可迭代的:
>>> import xml.etree.ElementTree as ET
>>> xml = "<root><a><b>....</b><c>....</c><d>....</d></a><d><c></c><a></a></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>
获取特定的孙元素:
Getting specific grandchild elements:
>>> root = ET.fromstring(xml)
>>> root.find("d")
[<Element 'd' at 0x10d7869a8>]
find()
方法将找到第一个匹配的子级。请注意,这仅仅是子元素。我们可以通过迭代孩子来找到孙子元素:
The find()
method will find the first matching child. Note how this is only the child element. We can find grandchildren elements by iterating the child:
>>> for e in root.find("d"):
... print(e)
...
<Element 'c' at 0x10d82ec28>
<Element 'a' at 0x10d82ec78>
如果要标记而不是ElementTree对象:
If you want the tag rather than the ElementTree object:
>>> [e.tag for e in root.find("d")]
['c', 'a']
请注意,<元素 c位于0x7fce44939650>
表示ElementTree Element
对象(与 root
相同),其API定义为在文档中
Note that <Element 'c' at 0x7fce44939650>
represents an ElementTree Element
object (same as root
), whose API is defined in the docs
这篇关于如何在Python中从Elementtree获取孙子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!