How to Modify an XML File in Python: A Comprehensive Guide

Modifying XML files in Python is a versatile feature, allowing you to update, add, or remove nodes and attributes. This guide uses Python's ElementTree library to demonstrate common XML modification tasks.

Code Breakdown:


import xml.etree.ElementTree as ET

Step 1: Import the ElementTree module, which is part of Python's standard library for handling XML files.


# Load the XML file
tree = ET.parse("sample.xml")
root = tree.getroot()

Step 2: Load the XML file into memory using ET.parse() and access the root element with getroot().

Updating Node Text


# Update text of a specific node
for student in root.findall("student"):
    id = student.find("id").text
    if id == "2":
        student.find("name").text = "Max Updated"

Explanation: This code locates the <student> node with id=2 and updates the text of the <name> child node to "Max Updated".

Adding a New Element


# Add a new child element
for student in root.findall("student"):
    grade = ET.SubElement(student, "grade")
    grade.text = "A"

Explanation: A new element <grade> is added as a child of each <student> node, with its text set to "A".

Removing an Element


# Remove a specific element
for student in root.findall("student"):
    mark = student.find("mark")
    if mark is not None:
        student.remove(mark)

Explanation: The <mark> element is removed from each <student> node if it exists.

Saving the Modified XML


# Save changes to a new XML file
tree.write("updated_sample.xml", encoding="utf-8", xml_declaration=True)

Explanation: The modified XML tree is written to a new file named updated_sample.xml, ensuring changes are saved with proper encoding.

Full Code Example:


import xml.etree.ElementTree as ET

# Load the XML file
tree = ET.parse("E:\\testing\\students.xml")
root = tree.getroot()

# Update text of a specific node
for student in root.findall("student"):
    id = student.find("id").text
    if id == "2":
        student.find("name").text = "Max Updated"

# Add a new child element
for student in root.findall("student"):
    grade = ET.SubElement(student, "grade")
    grade.text = "A"

# Remove a specific element
for student in root.findall("student"):
    mark = student.find("mark")
    if mark is not None:
        student.remove(mark)

# Save changes to a new XML file
tree.write("E:\\testing\\updated_sample.xml", encoding="utf-8", xml_declaration=True)

Sample Modified XML Output:


<students>
    <student>
        <id>1</id>
        <name>John Deo</name>
        <grade>A</grade>
    </student>
    <student>
        <id>2</id>
        <name>Max Updated</name>
        <grade>A</grade>
    </student>
</students>

Use Cases:

  • Updating XML configuration files dynamically.
  • Modifying API responses before further processing.
  • Editing hierarchical data for specific requirements.

Conclusion:

Python's ElementTree library provides a robust way to modify XML files, enabling tasks like updating, adding, or removing elements and attributes. This tutorial provides a foundational understanding for tackling XML modification tasks effectively.


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer