5

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 Answer 1

3

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. :-)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.