Skip to content Skip to sidebar Skip to footer

How To Generate An Xml File Via Python's Elementtree With Registered Namespaces Written In Output

I need to generate a XML file based on a given schema. This schema dictates I need to make use of a namespace prefix for the elements in the generated XML file. I need to use cElem

Solution 1:

To get a properly prefixed name, try using QName().

To write the XML with the XML declaration, try using xml_declaration=True in the ElementTree.write().

Example...

Python

import xml.etree.cElementTree as ET

ns = {"xs": "http://www.w3.org/2001/XMLSchema"}

ET.register_namespace('xs', ns["xs"])
root = ET.Element(ET.QName(ns["xs"], "House"))
ET.SubElement(root, ET.QName(ns["xs"], "Room"))

ET.ElementTree(root).write("output.xml", xml_declaration=True, encoding="utf-8")

XML Output

<?xml version='1.0' encoding='utf-8'?><xs:Housexmlns:xs="http://www.w3.org/2001/XMLSchema"><xs:Room /></xs:House>

Note: You don't have to use the ns dictionary. I just used it so I didn't have the full namespace uri everywhere.

Post a Comment for "How To Generate An Xml File Via Python's Elementtree With Registered Namespaces Written In Output"