user6223604
user6223604

Reputation:

How to insert a processing instruction in XML file?

I want to add a xml-stylesheet processing instruction before the root element in my XML file using ElementTree (Python 3.8).

You find as below my code that I used to create XML file

import xml.etree.cElementTree as ET

def Export_star_xml( self ):
        star_element = ET.Element("STAR",**{ 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance' })
        element_node = ET.SubElement(star_element ,"STAR_1")
        element_node.text = "Mario adam"
        tree.write( "star.xml" ,encoding="utf-8", xml_declaration=True )

Output:

<?xml version="1.0" encoding="windows-1252"?>
<STAR xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <STAR_1> Mario adam </STAR_1>
</STAR>    

Output Expected:

<?xml version="1.0" encoding="windows-1252"?>
<?xml-stylesheet type="text/xsl" href="ResourceFiles/form_star.xsl"?>
<STAR xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <STAR_1> Mario adam </STAR_1>
</STAR>

Upvotes: 2

Views: 1989

Answers (2)

ChrisG
ChrisG

Reputation: 1

The code below works under python 3.12.3 using xml.etree.ElementTree instead of xml.etree.cElementTree (which is deprecated):

import xml.etree.ElementTree as ET

top = ET.Element(None)
top.append(ET.ProcessingInstruction("xml-stylesheet", "href='ResourceFiles/form_star.xsl' type='text/xsl'"))

star_element = ET.SubElement(top,"STAR",**{ 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance' })
element_node = ET.SubElement(star_element ,"STAR_1")
element_node.text = "Mario adam"
tree = ET.ElementTree(top)
tree.write( "star.xml" ,encoding="utf-8", xml_declaration=True )

Result:

<?xml version='1.0' encoding='utf-8'?>
<?xml-stylesheet href='ResourceFiles/form_star.xsl' type='text/xsl'?>
<STAR xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <STAR_1>Mario adam</STAR_1>
</STAR>

Upvotes: 0

mzjn
mzjn

Reputation: 51032

I cannot figure out how to do this with ElementTree. Here is a solution that uses lxml, which provides an addprevious() method on elements.

from lxml import etree as ET

# Note the use of nsmap. The syntax used in the question is not accepted by lxml
star_element = ET.Element("STAR", nsmap={'xsi': 'http://www.w3.org/2001/XMLSchema-instance'})
element_node = ET.SubElement(star_element ,"STAR_1")
element_node.text = "Mario adam"

# Create PI and and insert it before the root element
pi = ET.ProcessingInstruction("xml-stylesheet", text='type="text/xsl" href="ResourceFiles/form_star.xsl"')
star_element.addprevious(pi)

ET.ElementTree(star_element).write("star.xml", encoding="utf-8",
                                   xml_declaration=True, pretty_print=True)

Result:

<?xml version='1.0' encoding='UTF-8'?>
<?xml-stylesheet type="text/xsl" href="ResourceFiles/form_star.xsl"?>
<STAR xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <STAR_1>Mario adam</STAR_1>
</STAR>

Upvotes: 4

Related Questions