3

使用 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 执行任何操作?

4

1 回答 1

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>
于 2012-11-30T16:13:36.517 回答