问题
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