Is there a way to register multiple namespaces using ElementTree

Viewed 1104

According to the docs, it seems like there can only be one namespace registered at a time.

xml.etree.ElementTree.register_namespace(prefix, uri)

Registers a namespace prefix. The registry is global, and any existing mapping for either the given prefix or the namespace URI will be removed. prefix is a namespace prefix. uri is a namespace uri. Tags and attributes in this namespace will be serialized with the given prefix, if at all possible.

But I was curious if anyone knows of some way around this? If there's nothing reasonable, I will switch to lxml.

1 Answers

You can register more than one namespace, just not in a single call to register_namespace().

You'd have to make separate calls to register_namespace() for each namespace.

Example...

import xml.etree.ElementTree as ET

ns_map = {"foo": "urn::foo",
          "bar": "urn::bar"}

for prefix, uri in ns_map.items():
    ET.register_namespace(prefix, uri)

root = ET.Element(ET.QName(ns_map["foo"], "root"))
ET.SubElement(root, ET.QName(ns_map["bar"], "child"))

print(ET.tostring(root).decode())

Prints...

<foo:root xmlns:bar="urn::bar" xmlns:foo="urn::foo"><bar:child /></foo:root>

Also...

If there's nothing reasonable, I will switch to lxml.

I'd switch to lxml anyway. :-)

Related