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

mid*_*ori 4 python xml xml-parsing python-2.7

我有一个XML文件,它有许多具有相同属性的不同节点.

我想知道是否可以使用Python和任何其他软件包(如minidom或ElementTree)找到所有这些节点.

ale*_*cxe 8

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

如果您想要所有具有特定属性的元素而不考虑属性值,则可以使用xpath表达式:

//tag[@attr]
Run Code Online (Sandbox Code Playgroud)

或者,如果你关心价值观:

//tag[@attr="value"]
Run Code Online (Sandbox Code Playgroud)

示例(使用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"]')]
Run Code Online (Sandbox Code Playgroud)

打印:

['1', '2', '5']
['1', '5']
Run Code Online (Sandbox Code Playgroud)