Find all nodes by attribute in XML using Python 2
I have an XML file with many different nodes with the same attribute.
I was wondering if all these nodes could be found using Python and any additional package like minidom or ElementTree.
+3
tinySandy
source
to share
2 answers
You can use the built-in module xml.etree.ElementTree
.
If you want all elements that have a specific attribute regardless of the attribute values, you can use the xpath expression:
//tag[@attr]
Or, if you want 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"]')]
Printing
['1', '2', '5']
['1', '5']
+7
alecxe
source
to share
This is a good example / start script with xpath:
# -*- 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)
+2
Gilles quenot
source
to share