在python中使用lxml添加xml前缀声明 [英] Adding xml prefix declaration with lxml in python

查看:428
本文介绍了在python中使用lxml添加xml前缀声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Short version : How to add the xmlns:xi="http://www.w3.org/2001/XInclude" prefix decleration to my root element in python with lxml ?

上下文:

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

I have some XML files that include IDs to other files.

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

These IDs represent the referenced file names.

使用lxml我设法用适当的XInclude语句替换了它们,但是如果我没有前缀declecle,我的XML解析器将不会添加包含,这是正常的.

Using lxml I managed to replace these with the appropriate XInclude statement, but if I do not have the prefix decleration my my XML parser won't add the includes, which is normal.

我不会包含我的代码,因为它不会帮助您理解问题.我可以很好地处理文档,我的问题是序列化.

Edit : I won't include my code because it won't help at understanding the problem. I can process the document just fine, my problem is serialization.

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

So from this <root> <somechild/> </root>

我想在输出文件中获取此<root xmlns:xi="http://www.w3.org/2001/XInclude"> <somechild/> </root>.

I want to get this <root xmlns:xi="http://www.w3.org/2001/XInclude"> <somechild/> </root> in my output file.

为此,我尝试使用

`

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是不可写的在尝试您的代码时给我作为错误.

Attribute nsmap is not writable gives me as error when I try your code.

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

You can try to register your namespace, remove current attributes (after saving them) of your root element, use set() method to add the namespace and recover the attributes.

一个例子:

>>> 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中使用lxml添加xml前缀声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆