How to Save XML Files in Python: A Comprehensive Guide

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.

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 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.

Saving the XML Data


# 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:

  • encoding="utf-8": Ensures the XML file supports international characters.
  • xml_declaration=True: Adds the XML declaration (e.g., <?xml version="1.0" encoding="utf-8"?>) at the top of the file.

Pretty Printing for Readability


# 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.

Full Code Example:


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))

Sample Output XML:


<students>
  <student>
    <id>1</id>
    <name>John Deo</name>
    <mark>75</mark>
  </student>
</students>

Use Cases:

  • Saving XML data for configuration files or structured storage.
  • Exporting data to XML for compatibility with other systems.
  • Generating XML reports from Python programs.

Conclusion:

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.


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