Data formats: XML, INI, TOML and pickle · 3 / 15 Theory

Creating and modifying XML

To produce XML you do not paste text with f-strings: an & or a < in a piece of data would break the document. You build the tree and the library escapes what is needed.

import xml.etree.ElementTree as ET

root = ET.Element("shop")
product = ET.SubElement(root, "product", {"id": "7"})
ET.SubElement(product, "name").text = "Coffee <ground> & more"
ET.SubElement(product, "price").text = "4.50"
print(ET.tostring(root, encoding="unicode"))
# <shop><product id="7"><name>Coffee &lt;ground&gt; &amp; more</name><price>4.50</price></product></shop>

product.find("price").text = "5.00"            # modify
product.set("sale", "yes")                      # add attribute
root.remove(product)                             # remove
print(len(root))                                  # 0

ET.indent(root)                                   # readable indentation (3.9+)
print(ET.tostring(root, encoding="unicode"))      # <shop />
  • ET.Element("x") creates the root and ET.SubElement(parent, "y", {attributes}) adds a child.
  • e.text = ... assigns the text (always a string). e.set("a", "v") adds or changes an attribute.
  • parent.remove(child) removes; parent.append(child) adds one already created.
  • ET.tostring(root, encoding="unicode") returns a str (without encoding it returns bytes). ET.indent() leaves it with readable indentation.
  • To save it to a file: ET.ElementTree(root).write("output.xml", encoding="utf-8", xml_declaration=True).

You practice it in Generate an XML document.