Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lxml tag name with a ":"

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"

like image 255
Adnan Avatar asked Dec 08 '11 14:12

Adnan


1 Answers

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

like image 78
dmzkrsk Avatar answered Nov 03 '22 13:11

dmzkrsk