How to create a simple XML file using Python?

Sometimes, we want to create a simple XML file using Python.

In this article, we’ll look at how to create a simple XML file using Python.

How to create a simple XML file using Python?

To create a simple XML file using Python, we can use the xml.etreer.cElementTree module.

For instance, we write

import xml.etree.cElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "doc")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"

tree = ET.ElementTree(root)
tree.write("filename.xml")

to create an element with the ET.Element class.

And we create a child element with the ET.SubElement class.

Then we set the text content of the elements by setting the text property to the values we want.

Then we create the DOM tree object with ET.ElementTree.

And we call write to write the file to the path we called write with.

Conclusion

To create a simple XML file using Python, we can use the xml.etreer.cElementTree module.