【问题标题】:Adding xml prefix declaration with lxml in python在python中使用lxml添加xml前缀声明
【发布时间】:2013-09-25 07:04:28
【问题描述】:

短版: 如何使用 lxml 将 xmlns:xi="http://www.w3.org/2001/XInclude" 前缀声明添加到我在 python 中的根元素中?

上下文

我有一些 XML 文件,其中包含其他文件的 ID。

这些 ID 代表引用的文件名。

使用 lxml 我设法将这些替换为适当的 XInclude 语句,但如果我没有前缀声明,我的 XML 解析器将不会添加包含,这是正常的。

编辑: 我不会包含我的代码,因为它无助于理解问题。我可以很好地处理文档,我的问题是序列化。

所以从这个 <root> <somechild/> </root>

我想在我的输出文件中得到这个<root xmlns:xi="http://www.w3.org/2001/XInclude"> <somechild/> </root>

为此,我尝试使用

`

tree = ET.parse(fileName)
root = tree.getroot() 
root.nsmap['xi'] = "http://www.w3.org/2001/XInclude"
tree.write('output.xml', xml_declaration=True, encoding="UTF-8", pretty_print=True)

`

【问题讨论】:

  • 你能分享一些代码来看看你是如何使用 lxml 的吗? lxml 文档有一些关于如何使用命名空间的示例:hereherehere

标签: python xml namespaces lxml xinclude


【解决方案1】:

属性nsmap 不可写 在我尝试您的代码时给我一个错误。

您可以尝试注册您的命名空间,删除根元素的当前属性(保存后),使用set() 方法添加命名空间并恢复属性。

一个例子:

>>> root = etree.XML('<root a1="one" a2="two"> <somechild/> </root>')
>>> etree.register_namespace('xi', 'http://www.w3.org/2001/XInclude')
>>> etree.tostring(root)
b'<root a1="one" a2="two"> <somechild/> </root>'
>>> orig_attrib = dict(root.attrib)
>>> root.set('{http://www.w3.org/2001/XInclude}xi', '')
>>> for a in root.attrib: del root.attrib[a]
>>> for a in orig_attrib: root.attrib[a] = orig_attrib[a]
>>> etree.tostring(root)
b'<root xmlns:xi="http://www.w3.org/2001/XInclude" a1="one" a2="two"> <somechild/> </root>'
>>> root.nsmap
{'xi': 'http://www.w3.org/2001/XInclude'}

【讨论】:

  • 感谢您的反馈。我现在无法测试它,但我会尽快回复您。同时,我进行了 XSLT 转换,将命名空间添加到任何 XML 根目录。我在我的根上调用这个转换,然后没关系,但你的解决方案似乎更简单。
猜你喜欢
  • 2015-01-31
  • 2015-08-16
  • 2017-11-05
  • 2013-08-12
  • 2013-08-29
  • 2021-12-07
  • 2020-06-24
  • 1970-01-01
相关资源
最近更新 更多