Parsing XML to Retrieve Node Attribute Instances
In the provided XML structure:
<foo> <bar> <type foobar="1"/> <type foobar="2"/> </bar> </foo>
The task is to extract the values of the "foobar" attribute for each "type" node.
Solution Using ElementTree
The ElementTree module offers a convenient way to parse XML and access node attributes. Here's how you can implement it:
import xml.etree.ElementTree as ET # Parse the XML root = ET.parse('input.xml').getroot() # Iterate over the "type" nodes for type_tag in root.findall('bar/type'): # Get the value of the "foobar" attribute value = type_tag.get('foobar') # Print the value print(value)
This code will print the values "1" and "2", as desired.
The above is the detailed content of How Can I Extract Attribute Values from XML Nodes Using Python's ElementTree?. For more information, please follow other related articles on the PHP Chinese website!