lxml tag name with a “:”

↘锁芯ラ 提交于 2019-12-01 01:29:38

问题


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"


回答1:


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



来源:https://stackoverflow.com/questions/8432912/lxml-tag-name-with-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!