Phrogz
Phrogz

Reputation: 303559

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?

Upvotes: 1

Views: 1552

Answers (2)

user6999902
user6999902

Reputation:

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>'

Upvotes: 4

alecxe
alecxe

Reputation: 474281

The most straightforward approach would be to not use the namespaces as is, but set the xmlns attribute explicitly:

from lxml import etree

root = etree.Element('root')
root.attrib["xmlns"] = "foo"

etree.SubElement(root, 'bar')

print(etree.tostring(root))

Prints:

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

Upvotes: 3

Related Questions