Before reading this article, you should read the article Read XML file with Python to understand the basic concepts of XML and how to read an XML file. With that knowledge, you can easily understand how to write an XML file in Python.
1. Write an XML file with ElementTree
The ElementTree module is a great tool to help write data to an XML file. The steps to create an XML file and write data to an XML file with ElementTree are as follows:
Step 1. Create a root tag in the XML file.
Step 2. Use the SubElement()
function to create child tags within the root tag with the following syntax:
SubElement(parent, tag, attrib={}, **extra)
In this context, parent is the name of the root tag, tag is the name of the child tag within the root tag, attrib is a dictionary containing attributes of the child tag, and extra contains additional attributes.
The SubElement()
function will return an object that is a new tag.
Step 3. We can use the set()
function to add attributes to the newly created tag. The text of a tag is assigned to the text attribute.
import xml.etree.ElementTree as ET
# create the file structure
data = ET.Element('data')
items = ET.SubElement(data, 'items')
item1 = ET.SubElement(items, 'item')
item2 = ET.SubElement(items, 'item')
item3 = ET.SubElement(items, 'item')
item1.set('name', 'item1')
item1.set('price', '5')
item2.set('name','item2')
item2.set('price','15')
item3.set('name', 'item3')
item3.set('price','20')
item1.text = 'book'
item2.text = 'chair'
item3.text = 'window'
# create a new XML file
mydata = ET.tostring(data, encoding='unicode')
myxmlfile = open("items2.xml", "w")
myxmlfile.write(mydata)
myxmlfile.close()
The content result of the items2.xml file was generated
<data><items><item name="item1" price="5">book</item><item name="item2" price="15">chair</item><item name="item3" price="20">window</item></items></data>
2. Write an XML file with minidom
The minidom library treats tags in an XML file as objects. The steps to create an XML file and write data to an XML file with minidom are as follows:
Step 1. Use the Document()
function to create an XML document.
Step 2. Create a root object representing the root tag in the XML file by using the createElement()
function. Append the root tag to the XML file using the appendChild()
function.
Step 3. Create child objects representing the child tags within the root tag and also with the createElement()
function. Use the setAttribute()
function to set attributes (if any) for the child tags.
Step 4. Append the child tags to the XML file using the appendChild()
function.
from xml.dom import minidom
# create a xml document
root = minidom.Document()
# create data tag as root tag
data = root.createElement('data')
root.appendChild(data)
# create child tag of data tag
items = root.createElement('items')
data.appendChild(items)
# create child tag of items
item1 = root.createElement('item')
item1.setAttribute('name', 'item1')
item1.setAttribute('price', '5')
item1.Text = 'book'
items.appendChild(item1)
item1Text = root.createTextNode("book")
item1.appendChild(item1Text)
item2 = root.createElement('item')
item2.setAttribute('name', 'item2')
item2.setAttribute('price', '15')
items.appendChild(item2)
item2Text = root.createTextNode("chair")
item2.appendChild(item2Text)
item3 = root.createElement('item')
item3.setAttribute('name', 'item3')
item3.setAttribute('price', '20')
items.appendChild(item3)
item3Text = root.createTextNode("window")
item3.appendChild(item3Text)
# create a new XML file
mydata = root.toprettyxml(indent ="\t")
myxmlfile = open("items2.xml", "w")
myxmlfile.write(mydata)
myxmlfile.close()
The content result of the items2.xml file was generated
<?xml version="1.0" ?>
<data>
<items>
<item name="item1" price="5">book</item>
<item name="item2" price="15">chair</item>
<item name="item3" price="20">window</item>
</items>
</data>
3. Write an XML file with BeautifulSoup
We can also use BeautifulSoup to create and write an XML file in Python. The steps to create an XML file and write data to an XML file with BeautifulSoup are as follows:
Step 1. Use the BeautifulSoup(features='xml')
function to create an empty XML document.
Step 2. Create a new tag by using the new_tag()
function. Append the new tag to the XML file using the append()
function.
Step 3. Create child tags within the created tag and also with the new_tag()
function. Use the string attribute to set text for child tags. Set attributes for child tags using square brackets [] and assign the value to that attribute.
Step 4. Append the child tags to the XML file using the append()
function.
from bs4 import BeautifulSoup
# create an empty xml document
soup = BeautifulSoup(features='xml')
# create data tag as root tag
data = soup.new_tag("data")
soup.append(data)
# create child tag of data tag
items = soup.new_tag("items")
data.append(items)
# create child tag of items
item1 = soup.new_tag('item')
item1.string = "book"
item1["name"] = "item1"
item1["price"] = "5"
items.append(item1)
item2 = soup.new_tag('item')
item2.string = "chair"
item2["name"] = "item2"
item2["price"] = "15"
items.append(item2)
item3 = soup.new_tag('item')
item3.string = "window"
item3["name"] = "item3"
item3["price"] = "20"
items.append(item3)
# create a new XML file
myxmlfile = open("items2.xml", "w")
myxmlfile.write(soup.prettify())
myxmlfile.close()
The content result of the items2.xml file was generated
<?xml version="1.0" encoding="utf-8"?>
<data>
<items>
<item name="item1" price="5">
book
</item>
<item name="item2" price="15">
chair
</item>
<item name="item3" price="20">
window
</item>
</items>
</data>