How to access the XML declaration with minidom (python) [duplicate]

孤者浪人 提交于 2020-01-07 07:20:13

问题


In python, with minidom, is it possible to read/modify the XML declaration?

I have a xml file which starts with

<?xml version="1.0" encoding='UTF-8' standalone='yes' ?>

and I'd like for e.g. to change it to

<?xml-stylesheet href='form.xslt' type='text/xsl' ?>

回答1:


You can have both <?xml ?> and <?xml-stylesheet ?> (they known as processing instructions, btw) in one XML. To add one, simply create an instance of ProcessingInstruction object and append it before the root element, for example :

from xml.dom import minidom

source = """<?xml version="1.0" ?>
<root/>"""
doc = minidom.parseString(source)
pi = doc.createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="form.xslt"')
doc.insertBefore(pi, doc.firstChild)
print(doc.toprettyxml())

output :

<?xml version="1.0" ?>
<?xml-stylesheet type="text/xsl" href="form.xslt"?>
<root/>


来源:https://stackoverflow.com/questions/31538586/how-to-access-the-xml-declaration-with-minidom-python

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