根元素是可迭代的:
>>> 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>
获取特定的孙子元素:
>>> root = ET.fromstring(xml)
>>> root.find("d")
[<Element 'd' at 0x10d7869a8>]
该find()
方法将找到第一个匹配的孩子。请注意这只是子元素。我们可以通过迭代子元素来找到孙元素:
>>> for e in root.find("d"):
... print(e)
...
<Element 'c' at 0x10d82ec28>
<Element 'a' at 0x10d82ec78>
如果您想要标签而不是 ElementTree 对象:
>>> [e.tag for e in root.find("d")]
['c', 'a']
请注意,它<Element 'c' at 0x7fce44939650>
表示一个 ElementTreeElement
对象(与 相同root
),其 API在文档中定义