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
source share