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

时间:2012-11-30 14:19:43

标签: groovy xml-parsing cdata

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

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

我解析文件并替换某些属性,如

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

然后在最后将更改写入像这样的新文件

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

这一切都很好,没问题,除非XML有CDATA,就像这样

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

结果是

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

问题是

如何让我的脚本不对CDATA做任何事情?

1 个答案:

答案 0 :(得分:0)

发现你可以做到:

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

获得输出:

<?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>