Find all nodes by attribute in XML using Python 2
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
source to share