Groovy and XML: Not able to insert processing instruction

Posted by rhellem on Stack Overflow See other posts from Stack Overflow or by rhellem
Published on 2012-12-08T20:30:46Z Indexed on 2012/12/08 23:04 UTC
Read the original article Hit count: 166

Filed under:
|

Scenario

Need to update some attributes in an existing XML-file. The file contains a XSL processing instruction, so when the XML is parsed and updated I need to add the instruction before writing it to a file again. Problem is - whatever I do - I'm not able to insert the processing instruction

Based on the Java-example found at rgagnon.com I have created the code below

Example code ##

import groovy.xml.*

def xml = '''|<something>
            |  <Settings>
            |  </Settings>
            |</something>'''.stripMargin()

def document = DOMBuilder.parse( new StringReader( xml ) )
def pi = document.createProcessingInstruction('xml-stylesheet', 'type="text/xsl"    href="Bp8DefaultView.xsl"');
document.insertBefore(pi, document.documentElement) 

println document.documentElement

Creates output

<?xml version="1.0" encoding="UTF-8"?>
<something>
  <Settings>
  </Settings>
</something>

What I want

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="Bp8DefaultView.xsl"?>
<something>
  <Settings>
  </Settings>
</something>

© Stack Overflow or respective owner

Related posts about Xml

Related posts about groovy