如何使用Python 2.6和minidom添加xml-stylesheet处理指令节点?

mon*_*nny 4 python xml stylesheet minidom processing-instruction

我正在使用minidom创建一个XML文档 - 如何确保我生成的XML文档包含这样的样式表引用:

<?xml-stylesheet type="text/xsl" href="mystyle.xslt"?>
Run Code Online (Sandbox Code Playgroud)

谢谢 !

mzj*_*zjn 8

使用这样的东西:

from xml.dom import minidom

xml = """
<root>
 <x>text</x>
</root>""" 

dom = minidom.parseString(xml)
pi = dom.createProcessingInstruction('xml-stylesheet',
                                     'type="text/xsl" href="mystyle.xslt"')
root = dom.firstChild
dom.insertBefore(pi, root)
print dom.toprettyxml()
Run Code Online (Sandbox Code Playgroud)

=>

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

   <x>
      text
   </x>

</root>
Run Code Online (Sandbox Code Playgroud)