74. Working with XML using xml.etree

Here are 10 Python code snippets demonstrating how to work with XML documents using the xml.etree.ElementTree module for parsing and creating XML files.


1. Parsing an XML String

This example shows how to parse an XML string into an ElementTree object and print the tag names.

import xml.etree.ElementTree as ET

xml_data = '''<root>
                    <child1>data1</child1>
                    <child2>data2</child2>
                </root>'''

# Parse XML string
root = ET.fromstring(xml_data)

# Access and print tag names
for child in root:
    print(child.tag, child.text)

2. Parsing an XML File

This example demonstrates how to parse an XML file using ElementTree.parse().


3. Creating an XML Document

This example shows how to create an XML document using ElementTree.


4. Finding Elements with XPath

This snippet demonstrates how to find elements using XPath expressions.


5. Modifying XML Elements

This example demonstrates how to modify an XML element's attributes and text content.


6. Setting Element Attributes

This example demonstrates how to add and modify attributes in XML elements.


7. Iterating Over XML Elements with Attributes

Here we show how to iterate over XML elements and access their attributes.


8. Converting XML Document to String

This example demonstrates how to convert an ElementTree object back to a string.


9. Pretty Printing an XML File

To make XML output more readable, you can use minidom for pretty printing.


10. Removing an Element from XML

This snippet demonstrates how to remove an element from an XML document.


These code snippets illustrate how to work with XML data using the xml.etree.ElementTree module. You can use this module to parse, modify, create, and write XML documents efficiently in Python.

Last updated