我正在尝试使用lxml.etree从JSON对象创建xml树.一些标记名在它们中继续冒号,例如:-
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'
'settings:current' I tried using
'{settings} current'作为标签名称,但是我得到了:-
'{settings}current' as the tag name but I get this :-
ns0:当前xmlns:ns0 =设置"
ns0:current xmlns:ns0="settings"
推荐答案是的,首先阅读并了解XML名称空间.然后使用它生成带有名称空间的XML树:u
Yes, first read and understand XML namespaces. Then use that to generate XML-tree with namespaces:u
>>> MY_NAMESPACES={'settings': 'example/url-for-settings-namespace'} >>> e=etree.Element('{%s}current' % MY_NAMESPACES['settings'], nsmap=MY_NAMESPACES) >>> etree.tostring(e) '<settings:current xmlns:settings="example/url-for-settings-namespace"/>'您可以将其与默认名称空间结合起来
And you can combine that with default namespaces
>>> MY_NAMESPACES={'settings': 'example/url-for-settings-namespace', None: 'example/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="example/url-for-settings-namespace" xmlns="example/url-for-default-namespace"><some-element><settings:current/></some-element></my-root>'请注意,您必须在XML树层次结构中具有一个带有nsmap=MY_NAMESPACES的元素.然后所有后代节点都可以使用该声明.在您的情况下,您没有什么用,所以lxml生成名称空间名称,例如ns0
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
此外,当您创建新节点时,请使用名称空间URI作为标记名称,而不是名称空间名称:{example/url-for-settings-namespace}current
Also, when you create a new node use namespace URI for tag name, not namespace name: {example/url-for-settings-namespace}current
更多推荐
具有“:"的lxml标记名称
发布评论