使用Python 2按XML中的属性查找所有节点


问题内容

我有一个XML文件,其中有许多具有相同属性的不同节点。

我想知道是否有可能使用Python和minidom或ElementTree之类的其他软件包来找到所有这些节点。


问题答案:

您可以使用内置xml.etree.ElementTree模块。

如果希望所有具有特定属性的元素,而与属性值无关,则可以使用 xpath表达式

//tag[@attr]

或者,如果您关心值:

//tag[@attr="value"]

示例(使用findall()方法):

import xml.etree.ElementTree as ET

data = """
<parent>
    <child attr="test">1</child>
    <child attr="something else">2</child>
    <child other_attr="other">3</child>
    <child>4</child>
    <child attr="test">5</child>
</parent>
"""

parent = ET.fromstring(data)
print [child.text for child in parent.findall('.//child[@attr]')]
print [child.text for child in parent.findall('.//child[@attr="test"]')]

印刷品:

['1', '2', '5']
['1', '5']