← retour aux snippets

xml.etree.ElementTree: construire et écrire du XML

Créer un arbre XML et le sérialiser proprement.

python xml #xml#build

objectif

Créer un arbre XML et le sérialiser proprement.

code minimal

import xml.etree.ElementTree as ET
root = ET.Element("root")
ET.SubElement(root, "item", attrib={"id":"1"}).text = "hello"
xml = ET.tostring(root, encoding="unicode")
print("<item" in xml and "hello" in xml)  # attendu: True

utilisation

import xml.etree.ElementTree as ET, io
root = ET.Element("data"); ET.SubElement(root, "row").text = "x"
tree = ET.ElementTree(root)
buf = io.BytesIO(); tree.write(buf, encoding="utf-8", xml_declaration=True)
print(buf.getvalue().startswith(b"<?xml"))

variante(s) utile(s)

import xml.etree.ElementTree as ET
print(hasattr(ET, "SubElement"))

notes

  • Pour namespaces, utilisez ET.register_namespace et des noms qualifiés.
  • Pour gros XML, préférez iterparse pour le streaming.