【问题标题】:Find all nodes by attribute in XML using Python 2使用 Python 2 在 XML 中按属性查找所有节点
【发布时间】:2015-01-07 03:04:02
【问题描述】:

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

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

【问题讨论】:

  • 谢谢大家,我用的是minidom,好像没那么强大,终于要移到ElementTree了。

标签: python xml python-2.7 xml-parsing


【解决方案1】:

您可以使用内置的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']

【讨论】:

  • 为什么假设所有这些节点都是根元素的直接子节点?如果 children and grandchildren 或任何嵌套级别的后代都具有这些属性怎么办? parent.findall('.//[@attr]') 在 Python 2.7 中抛出一个无效的后代错误。
  • @alex wait, //.// 将在任何嵌套级别查找节点。或者,我误解了你的问题..谢谢。
  • @alex 啊,如果您要查找任何节点名称,请使用.//*[@attr]
【解决方案2】:

这是一个使用 的很好的示例/启动脚本:

# -*- 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多