Reputation: 869
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
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>
Upvotes: 0
Views: 815
Reputation: 122394
You're inserting the PI before the documentElement
, but then passing only the element to println
. Does it work if you print the whole document
?
Failing that, the "official" way to output a DOM document is to use LSSerializer
def ser = document.implementation.createLSSerializer()
new File("output.xml").withOutputStream { o ->
def lso = document.implementation.createLSOutput()
lso.byteStream = o
ser.write(document, lso)
}
Upvotes: 1