Saving XML files is a crucial part of working with XML data. Python's ElementTree library makes it simple to write XML data to files, complete with optional formatting and encoding. This guide demonstrates how to save XML files step by step.
import xml.etree.ElementTree as ET
Step 1: Import the ElementTree module, which is part of Python's standard library for handling XML data.
# Create XML data
root = ET.Element("students")
student1 = ET.SubElement(root, "student")
ET.SubElement(student1, "id").text = "1"
ET.SubElement(student1, "name").text = "John Deo"
ET.SubElement(student1, "mark").text = "75"
Step 2: Define your XML structure programmatically using ElementTree. Here, we create a root element <students> and add a child <student> with attributes.
# Save the XML to a file
tree = ET.ElementTree(root)
tree.write("output.xml", encoding="utf-8", xml_declaration=True)
Explanation: Use ET.ElementTree to create an XML tree object and save it to a file named output.xml. The parameters:
# Pretty-print the XML before saving
from xml.dom import minidom
def prettify(elem):
rough_string = ET.tostring(elem, encoding="utf-8")
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ")
# Save pretty-printed XML
with open("pretty_output.xml", "w") as file:
file.write(prettify(root))
Explanation: The minidom module provides a way to format XML for better readability. This creates an indented, human-readable XML file.
import xml.etree.ElementTree as ET
from xml.dom import minidom
# Create XML data
root = ET.Element("students")
student1 = ET.SubElement(root, "student")
ET.SubElement(student1, "id").text = "1"
ET.SubElement(student1, "name").text = "John Deo"
ET.SubElement(student1, "mark").text = "75"
# Save the XML to a file
tree = ET.ElementTree(root)
tree.write("E:\\testing\\output.xml", encoding="utf-8", xml_declaration=True)
# Pretty-print the XML and save it
def prettify(elem):
rough_string = ET.tostring(elem, encoding="utf-8")
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ")
with open("E:\\testing\\pretty_output.xml", "w") as file:
file.write(prettify(root))
<students>
<student>
<id>1</id>
<name>John Deo</name>
<mark>75</mark>
</student>
</students>
Python makes it easy to save XML files with optional formatting using ElementTree. This tutorial provides a foundation for saving XML data effectively while ensuring compatibility with different systems.