Introduction to Python’s xml.etree.ElementTree Module
Python’s xml.etree.ElementTree module is a part of Python’s Standard Library that provides a lightweight and efficient API for parsing and creating XML. This module treats XML as trees of nodes, which makes it intuitive and easy to work with.
How to Parse XML with xml.etree.ElementTree
Parsing XML is straightforward with the xml.etree.ElementTree module. Here’s a basic example:
import xml.etree.ElementTree as ET
tree = ET.parse('example.xml')
root = tree.getroot()
This code reads an XML file and gets its root element.
Finding Elements in XML
You can find elements in an XML document using the find() method:
for child in root:
print(child.tag, child.attrib)
This code prints the tag and attributes of each child of the root.
Modifying Elements in XML
You can modify elements by changing their text or attributes, or by adding new elements:
for elem in root.iter('foo'):
elem.text = 'bar'
This code changes the text of all ‚foo‘ elements to ‚bar‘.
Creating New XML Documents
You can create new XML documents using the ElementTree module:
a = ET.Element('a')
b = ET.SubElement(a, 'b')
c = ET.SubElement(a, 'c')
tree = ET.ElementTree(a)
tree.write('output.xml')
This code creates a new XML document with a root ‚a‘ and two children ‚b‘ and ‚c‘.
Conclusion
Python’s xml.etree.ElementTree module is a powerful tool for working with XML. Its intuitive API and efficient performance make it a great choice for any Python programmer who needs to parse, modify, or create XML documents.