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.
Copy
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().
Copy
3. Creating an XML Document
This example shows how to create an XML document using ElementTree.
Copy
4. Finding Elements with XPath
This snippet demonstrates how to find elements using XPath expressions.
Copy
5. Modifying XML Elements
This example demonstrates how to modify an XML element's attributes and text content.
Copy
6. Setting Element Attributes
This example demonstrates how to add and modify attributes in XML elements.
Copy
7. Iterating Over XML Elements with Attributes
Here we show how to iterate over XML elements and access their attributes.
Copy
8. Converting XML Document to String
This example demonstrates how to convert an ElementTree object back to a string.
Copy
9. Pretty Printing an XML File
To make XML output more readable, you can use minidom for pretty printing.
Copy
10. Removing an Element from XML
This snippet demonstrates how to remove an element from an XML document.
Copy
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