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.
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().
# 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".
# 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".
# 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.
# 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.
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)
<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>
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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.