Python XML Processing (ElementTree)
XML (eXtensible Markup Language) is a markup language similar to HTML, but without predefined tags. Python's xml.etree.ElementTree module provides a simple and efficient API for parsing and creating XML data.
Importing the Module
import xml.etree.ElementTree as ET
Parsing XML
From a String
import xml.etree.ElementTree as ET
data = """
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
</data>
"""
root = ET.fromstring(data)
print(root.tag) # Output: data
From a File
import xml.etree.ElementTree as ET
# Assuming 'country_data.xml' exists
# tree = ET.parse('country_data.xml')
# root = tree.getroot()
Accessing Elements
You can access child elements by index or iterate over them.
# Accessing child by index
country = root[0]
rank = country.find('rank').text
print(rank) # Output: 1
Attributes are accessed as a dictionary.
print(root[0].attrib)
# Output: {'name': 'Liechtenstein'}
Finding Elements
find()
Returns the first matching element.
rank = root.find(".//rank")
print(rank.text)
findall()
Returns a list of all matching elements.
for neighbor in root.iter('neighbor'):
print(neighbor.attrib)
Modifying XML
You can modify text, attributes, and tags directly.
for rank in root.iter('rank'):
new_rank = int(rank.text) + 1
rank.text = str(new_rank)
rank.set('updated', 'yes')
Creating XML
You can create XML trees from scratch.
import xml.etree.ElementTree as ET
a = ET.Element('a')
b = ET.SubElement(a, 'b')
c = ET.SubElement(a, 'c')
c.text = 'Some text'
print(ET.tostring(a, encoding='unicode'))
# Output: <a><b /><c>Some text</c></a>