python - 在python中使用lxml添加xml前缀声明

标签 python xml namespaces lxml xinclude

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

上下文:

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

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

使用 lxml,我设法用适当的 XInclude 语句替换它们,但如果我没有前缀 decleration,我的 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)

`

最佳答案

属性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'}

关于python - 在python中使用lxml添加xml前缀声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18998352/

相关文章:

c# - 一个关于 LINQ to XML 的简单问题

Python ctypes 和没有足够的参数(缺少 4 个字节)

python - 在docker容器中为django运行cron作业时manage.py脚本中出现错误

java - 无法锁定方向;可能的修复?

c# - 访问类

namespaces - JAXB 命名空间问题

python - 带时区到纪元的日期时间

python - [ :] in python 是什么意思

xml - 上传时 Amazon S3 存储桶 MalformedXML 错误

ios - 将 NSData 转换为 NSDictionary