Creating a simple XML file using python

These days, the most popular (and very simple) option is the ElementTree API, which has been included in the standard library since Python 2.5. The available options for that are:

  • ElementTree (Basic, pure-Python implementation of ElementTree. Part of the standard library since 2.5)
  • cElementTree (Optimized C implementation of ElementTree. Also offered in the standard library since 2.5)
  • LXML (Based on libxml2. Offers a a rich superset of the ElementTree API as well XPath, CSS Selectors, and more)

Example

import xml.etree.cElementTree as ET

root = ET.Element("root")

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

field1 = ET.SubElement(doc, "person1")
field1.set("name", "First Name")
field1.text = "John"

field2 = ET.SubElement(doc, "person2")
field2.set("name", "First Name")
field2.text = "charles"

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

Output (anyFile.xml)

<root>
	<person>
		<person1 name="First Name">John</person1>
		<person2 name="First Name">charles</person2>
	</person>
</root>