Phrogz Phrogz - 10 months ago 72
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 />

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')
#=> 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 Source

Use the nsmap parameter, which is described on

from lxml import etree

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


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