具有“:"的lxml标记名称

编程入门 行业动态 更新时间:2024-10-23 09:25:30
本文介绍了具有“:"的lxml标记名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用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标记名称

本文发布于:2023-11-12 12:36:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581509.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:标记   名称   quot   lxml

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!