1

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?

3
  • 1
    read lxml.de/tutorial.html#namespaces Commented Nov 1, 2016 at 18:41
  • @LutzHorn Perhaps I'm missing a sentence, but that tutorial (which I've read) only describes how to query against a default namespace, not how to get serialization to emit a default namespace. Commented Nov 1, 2016 at 18:44
  • 1
    Read again :) (or read my answer below) Commented Nov 1, 2016 at 18:48

2 Answers 2

4

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>'
Sign up to request clarification or add additional context in comments.

1 Comment

This works in terms of the printed result, i.e. after serialization. However, is not quite correct. Actually giving the namespace explicitly does not look nice but is correct. For details see discussion here: github.com/lxml/lxml/pull/136
3

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>

1 Comment

I probably won't accept this answer, because it's a dirty hack, but I will almost certainly end up using this answer in my code because it's a delightfully dirty hack.

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.