all Python 3xml.etree.ElementTreefunction
xml.etree.ElementTree.register_namespace()
namespaces
Sets the prefix used for a namespace on output instead of the automatic ns0, ns1.
Syntax
ET.register_namespace(prefix, uri)
After parsing, tags are stored as '{uri}tag' and the original prefixes are lost, so writing back gives ns0:…, hence 'broken' files. register_namespace() fixes the output, but the registry is global for the process: registering in one library changes output in another. Searching is unaffected: find('item') in a document with a default xmlns returns None; use '{uri}item', a namespaces dict or '{*}item' (3.8+).
Examples
import xml.etree.ElementTree as ET
root = ET.fromstring('<root xmlns="http://ex.com/ns"><item>1</item></root>')
print(root.tag) # → {http://ex.com/ns}root
print(root.find('item')) # → None
print(root.find('ns:item', {'ns': 'http://ex.com/ns'}).text) # → 1
print(root.find('{*}item').text) # → 1
import xml.etree.ElementTree as ET
root = ET.fromstring('<root xmlns="http://ex.com/ns"><item/></root>')
print(ET.tostring(root, encoding='unicode'))
# → <ns0:root xmlns:ns0="http://ex.com/ns"><ns0:item /></ns0:root>
ET.register_namespace('', 'http://ex.com/ns')
print(ET.tostring(root, encoding='unicode'))
# → <root xmlns="http://ex.com/ns"><item /></root>
See also
Open in the full glossarydocs.python.orgReport an inaccuracy