4

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 !

Kev
  • 118,037
  • 53
  • 300
  • 385
monojohnny
  • 5,894
  • 16
  • 59
  • 83

3 Answers3

8

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>
mzjn
  • 48,958
  • 13
  • 128
  • 248
2

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.

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
0
import xml.dom
dom = xml.dom.minidom.parse("C:\\Temp\\Report.xml")
pi = dom.createProcessingInstruction('xml-stylesheet',
                                     'type="text/xsl" href="TestCaseReport.xslt"')
root = dom.firstChild
dom.insertBefore(pi, root)
a = dom.toxml()
f = open("C:\\Report(1).xml",'w')
f.write(a)
f.close()
  • Welcome to StackOverflow. While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit](https://stackoverflow.com/posts/64340533/edit) your answer to add explanations and give an indication of what limitations and assumptions apply. – Ruli Nov 10 '20 at 12:19