使用Python 2在XML中按属性查找所有节点(Find all nodes by attribute in XML using Python 2)

编程入门 行业动态 更新时间:2024-10-28 09:12:53
使用Python 2在XML中按属性查找所有节点(Find all nodes by attribute in XML using Python 2)

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

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

I have an XML file which has a lot of different nodes with the same attribute.

I was wondering if it's possible to find all these nodes using Python and any additional package like minidom or ElementTree.

最满意答案

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

You can use built-in xml.etree.ElementTree module.

If you want all elements that have a particular attribute regardless of the attribute values, you can use an xpath expression:

//tag[@attr]

Or, if you care about values:

//tag[@attr="value"]

Example (using 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"]')]

Prints:

['1', '2', '5'] ['1', '5']

更多推荐

节点,Python,nodes,XML,电脑培训,计算机培训,IT培训"/> <meta name="descripti

本文发布于:2023-07-19 09:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1176871.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:节点   属性   XML   Python   nodes

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!