Python - How to write XML file

By xngo on June 16, 2019

Up until now I have shown How to read XML file but haven't shown how to write XML file. As always with Python, there are different ways to write XML file. I will show you the simplest way using the xml.etree.ElementTree, which has been included in the standard library since Python 2.5.

#!/usr/bin/python3
 
import xml.etree.ElementTree as ET
 
# Create root element.
root = ET.Element("root")
 
# Add sub element.
country = ET.SubElement(root, "country", name="Canada")
 
# Add sub-sub element.
quebec = ET.SubElement(country, "province")
quebec.text = "Quebec"
 
ontario = ET.SubElement(country, "province")
ontario.text = "Ontario"
ontario.set("rank", "2")    # Set attribute rank="2"
 
# One-liner to create Alberta province.
ET.SubElement(country, "province", rank="3", category="oil").text = "Alberta"
 
# Write XML file.
tree = ET.ElementTree(root)
tree.write("canada.xml")

Print pretty

The XML file created is very hard to read because all the XML tags are in 1 line. You can use minidom to indent and reformat the XML tags nicely so that is easy to read and understand. Here is the code to make your XML output visually appealing.

# Print pretty
from xml.dom import minidom
xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent="   ")
with open("canada-pretty.xml", "w") as f:
    f.write(xmlstr)

Output

<?xml version="1.0" ?>
<root>
   <country name="Canada">
      <province>Quebec</province>
      <province rank="2">Ontario</province>
      <province category="oil" rank="3">Alberta</province>
   </country>
</root>

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.