gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 02:01:04 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

//tag[@attr]

或者,如果您关心值(value)观:

//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']

关于python - 使用 Python 2 在 XML 中按属性查找所有节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27810825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com