Working with XML Files

XML (eXtensible Markup Language) is a popular markup language designed to store and transport data with a self-descriptive and hierarchical structure.

Why Use XML?

Key XML Concepts

Working with XML in Python

Common Use Cases

10 Python XML Examples

Example 1: Parsing an XML file

import xml.etree.ElementTree as ET

tree = ET.parse('data.xml')
root = tree.getroot()
print(root.tag)

Example 2: Iterating over child elements

for child in root:
    print(child.tag, child.attrib)

Example 3: Accessing element text and attributes

for elem in root.findall('item'):
    name = elem.find('name').text
    price = elem.get('price')
    print(f"Name: {name}, Price: {price}")

Example 4: Creating a new XML element

new_item = ET.Element('item', attrib={'price': '9.99'})
name = ET.SubElement(new_item, 'name')
name.text = 'New Product'

Example 5: Adding the new element to the tree

root.append(new_item)
tree.write('updated_data.xml')

Example 6: Modifying an element’s text

for item in root.findall('item'):
    if item.find('name').text == 'Old Product':
        item.find('name').text = 'Updated Product'
tree.write('updated_data.xml')

Example 7: Removing an element

for item in root.findall('item'):
    if item.get('price') == '0':
        root.remove(item)
tree.write('cleaned_data.xml')

Example 8: Finding elements using XPath

items = root.findall(".//item[@price='9.99']")
for item in items:
    print(item.find('name').text)

Example 9: Parsing XML from a string

xml_data = """<store><item price="5.99"><name>Sample</name></item></store>"""
root = ET.fromstring(xml_data)
print(root.tag)

Example 10: Writing a new XML file from scratch

root = ET.Element('store')
item = ET.SubElement(root, 'item', attrib={'price': '15.99'})
name = ET.SubElement(item, 'name')
name.text = 'Brand New Item'

tree = ET.ElementTree(root)
tree.write('new_store.xml')