您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

您可以使用内置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']
python 2022/1/1 18:44:01 有298人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶