使用Groovy解析XML:解析XML文件时如何保留CDATA [英] Parse XML using Groovy: How do I keep the CDATA when parsing a XML file
本文介绍了使用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>
这篇关于使用Groovy解析XML:解析XML文件时如何保留CDATA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文