Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an xml-stylesheet processing instruction node with Python 2.6 and minidom?

I'm creating an XML document using minidom - how do I ensure my resultant XML document contains a stylesheet reference like this:

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

Thanks !

like image 522
monojohnny Avatar asked Dec 28 '22 22:12

monojohnny


2 Answers

Use something like this:

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

=>

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

   <x>
      text
   </x>

</root>
like image 141
mzjn Avatar answered Apr 07 '23 20:04

mzjn


I am not familiar with minidom, but you must create a processing instruction node (PI) with name: "xml-stylesheet" and text: "type='text/xsl' href='mystyle.xslt'"

Read the documentation how a PI is created.

like image 39
Dimitre Novatchev Avatar answered Apr 07 '23 20:04

Dimitre Novatchev