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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With