我有一个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
发布评论