Phrogz Phrogz - 1 month ago 20
Python Question

Generate XML that uses a default namespace

I want to use Python and lxml to generate XML like the following:

<root xmlns="foo">
<bar />
</root>


However, the following code creates XML that is semantically identical, but uses ugly auto-generated namespace prefixes instead:

from lxml import etree
root = etree.Element('{foo}root')
etree.SubElement(root,'{foo}bar')
print(etree.tostring(root))
#=> b'<ns0:root xmlns:ns0="foo"><ns0:bar/></ns0:root>'


How do I get lxml/etree to generate XML using a single default namespace on the root element, with no namespace prefixes on any descendant elements?

Answer

Use the nsmap parameter, which is described on http://lxml.de/tutorial.html#namespaces

from lxml import etree

nsmap = {None: "foo"}
root = etree.Element('{foo}root', nsmap=nsmap)
etree.SubElement(root,'{foo}bar')
print(etree.tostring(root))

Output

b'<root xmlns="foo"><bar/></root>'
Comments