Name of the lxml tag with the name ":"

I am trying to create an xml tree from a JSON object using lxml.etree. Some of the tags carry a colon: -

': current' I tried using

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

ns0: current xmlns: ns0 = "settings"

+4
source share
1 answer

Yes, read and understand the XML namespaces first. Then use this to generate an 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 this with the default namespace

 >>> 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 in the XML tree hierarchy, you must have an element with nsmap=MY_NAMESPACES . Then all descendand nodes can use this ad. In your case, you do not have this bit, so lxml generates namespace names like ns0

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

+6
source

Source: https://habr.com/ru/post/1385350/


All Articles