lxml tag name with a ":"
Asked Answered
B

1

8

I am trying to create an xml tree from a JSON object using lxml.etree. Some of the tagnames contin a colon in them something like :-

'settings:current' I tried using

'{settings}current' as the tag name but I get this :-

ns0:current xmlns:ns0="settings"

Barbiturate answered 8/12, 2011 at 14:57 Comment(1)
Take some time to learn the basics of XML namespaces. Then read lxml.de/tutorial.html#namespaces.Barca
A
14

Yes, first read and understand XML namespaces. Then use that to generate XML-tree with namespaces:u

>>> MY_NAMESPACES={'settings': 'http://example.com/url-for-settings-namespace'}
>>> e=etree.Element('{%s}current' % MY_NAMESPACES['settings'], nsmap=MY_NAMESPACES)
>>> etree.tostring(e)
'<settings:current xmlns:settings="http://example.com/url-for-settings-namespace"/>'

And you can combine that with default namespaces

>>> MY_NAMESPACES={'settings': 'http://example.com/url-for-settings-namespace', None:    'http://example.com/url-for-default-namespace'}
>>> r=etree.Element('my-root', nsmap=MY_NAMESPACES)
>>> d=etree.Element('{%s}some-element' % MY_NAMESPACES[None])
>>> e=etree.Element('{%s}current' % MY_NAMESPACES['settings'])
>>> d.append(e)
>>> r.append(d)
>>> etree.tostring(r)
'<my-root xmlns:settings="http://example.com/url-for-settings-namespace" xmlns="http://example.com/url-for-default-namespace"><some-element><settings:current/></some-element></my-root>'

Note, that you have to have an element with nsmap=MY_NAMESPACES in your XML-tree hierarchy. Then all descendand nodes can use that declaration. In your case, you have no that bit, so lxml generates namespaces names like ns0

Also, when you create a new node use namespace URI for tag name, not namespace name: {http://example.com/url-for-settings-namespace}current

Avoid answered 26/1, 2012 at 2:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.