如何使用 minidom (python) 访问 XML 声明

How to access the XML declaration with minidom (python)

在 python 中,使用 minidom,是否可以 read/modify XML 声明?

我有一个以

开头的 xml 文件
<?xml version="1.0" encoding='UTF-8' standalone='yes' ?>

我想要例如将其更改为

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

您可以将 <?xml ?><?xml-stylesheet ?>(它们称为 处理指令 ,顺便说一句)合二为一 XML。要添加一个,只需创建一个 ProcessingInstruction 对象的实例并将其附加到根元素之前,例如 :

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())

输出:

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