使用Groovy解析XML:解析XML文件时如何保留CDATA

问题描述:

使用Groovy 2.0.5 JVM 1.6.0_31,我创建了一个脚本,它将现有的XML文件作为输入

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)

所有这些没问题,除非XML有CDATA,像这样

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>



问题是



如何获得我的脚本不会对CDATA做任何事情?

Question is

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

发现您可以这样做:

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>