使用 Python 2 按属性在 XML 中查找所有节点
Find all nodes by attribute in XML using Python 2
我有一个 XML 文件,其中有许多具有相同属性的不同节点。
我想知道是否可以使用 Python 和任何其他包(如 minidom 或 ElementTree)找到所有这些节点。
这是一个很好的 sample/start 脚本,使用 xpath :
# -*- coding: utf-8 -*-
from lxml import etree
fp = open("xml.xml")
tree = etree.parse(fp)
for el in tree.findall('//node[@attr="something"]'):
print(el.text)
您可以使用内置的 xml.etree.ElementTree
模块。
如果您想要所有具有特定属性的元素而不考虑属性值,您可以使用 xpath 表达式:
//tag[@attr]
或者,如果您关心价值观:
//tag[@attr="value"]
示例(使用 findall()
method):
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']
我有一个 XML 文件,其中有许多具有相同属性的不同节点。
我想知道是否可以使用 Python 和任何其他包(如 minidom 或 ElementTree)找到所有这些节点。
这是一个很好的 sample/start 脚本,使用 xpath :
# -*- coding: utf-8 -*-
from lxml import etree
fp = open("xml.xml")
tree = etree.parse(fp)
for el in tree.findall('//node[@attr="something"]'):
print(el.text)
您可以使用内置的 xml.etree.ElementTree
模块。
如果您想要所有具有特定属性的元素而不考虑属性值,您可以使用 xpath 表达式:
//tag[@attr]
或者,如果您关心价值观:
//tag[@attr="value"]
示例(使用 findall()
method):
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']