Adding xml prefix declaration with lxml in python

最后都变了- 提交于 2020-02-05 03:44:05

问题


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

Context :

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

These IDs represent the referenced file names.

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.

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

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

For this I tried using

`

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)

`


回答1:


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

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.

An example:

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


来源:https://stackoverflow.com/questions/18998352/adding-xml-prefix-declaration-with-lxml-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!