Modify XML declaration with python

☆樱花仙子☆ 提交于 2019-12-02 21:00:50

问题


I have an XML document for which I need to add a couple of things to the XML declaration using minidom. The declaration looks like this:

<?xml version="1.0"?>

And I need it to look like this:

<?xml version="1.0" encoding="UTF-16" standalone="no"?>

I know how to change or add attributes using minidom, which will not work here.

What is the easiest way of doing this? For reference, I am running python 3.3.3.


回答1:


I'm not sure if this can be done with minidom. But you could try lxml.

from lxml import etree

tree = etree.parse("test.xml")
string = etree.tostring(tree.getroot(), pretty_print = True, xml_declaration = True, standalone = False, encoding = "UTF-16")
with open("test2.xml", "wb") as f:
    f.write(string)

More or less taken from here.



来源:https://stackoverflow.com/questions/25498838/modify-xml-declaration-with-python

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