3

Using Groovy 2.0.5 JVM 1.6.0_31, I have created a script that takes an existing XML-file as input

def root = new XmlParser().parse(new File('filename'))

I parse the file and replaces certain attributes like this

root.Settings.Setting.each {
if (it.'@NAME' =~ 'CASEID_SEQUENCE_SIZE') {
   it.'@VALUE' = '100' 

And then at the end writes the changes to a new file like this

def outputfile = new File( levelConfig.RESULTFILE )
new XmlNodePrinter(new PrintWriter(outputfile)).print(root)

All this is fine, no problem, except when the XML has CDATA, like this

<HandlerURL>
   <![CDATA[admin/MainWindow.jsp]]>
</HandlerURL>

the result is then

<HandlerURL>
    admin/MainWindow.jsp
</HandlerURL>

Question is

How can I get my script to not do anything with the CDATA?

rhellem
  • 769
  • 1
  • 11
  • 26
  • Had to change the write to file code to XmlUtil.serialize( root , new PrintWriter(outputfile)) or else the XML was just cut off somewhere in the middle of the file – rhellem Dec 03 '12 at 08:54

1 Answers1

0

Found you can do:

import groovy.xml.*
import groovy.xml.dom.DOMCategory

def xml = '''<root>
            |  <Settings>
            |    <Setting name="CASEID_SEQUENCE_SIZE">
            |      <HandlerURL>
            |        <![CDATA[ admin/MainWindow.jsp ]]>
            |      </HandlerURL>
            |    </Setting>
            |    <Setting name="SOMETHING_ELSE">
            |      <HandlerURL>
            |        <![CDATA[ admin/MainWindow.jsp ]]>
            |      </HandlerURL>
            |    </Setting>
            |  </Settings>
            |</root>'''.stripMargin()

def document = DOMBuilder.parse( new StringReader( xml ) )
def root = document.documentElement

use(DOMCategory) {
  root.Settings.Setting.each {
    if( it.'@name' == 'CASEID_SEQUENCE_SIZE' ) {
      it[ '@value' ] = 100
    }
  }
}

def result = XmlUtil.serialize( root )

println result

To get the output:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <Settings>
    <Setting name="CASEID_SEQUENCE_SIZE" value="100">
      <HandlerURL>
        <![CDATA[ admin/MainWindow.jsp ]]>
      </HandlerURL>
    </Setting>
    <Setting name="SOMETHING_ELSE">
      <HandlerURL>
        <![CDATA[ admin/MainWindow.jsp ]]>
      </HandlerURL>
    </Setting>
  </Settings>
</root>
tim_yates
  • 167,322
  • 27
  • 342
  • 338