将XML代码段插入Groovy中的另一个XML文档中 [英] Inserting XML snippet into another XML document in Groovy
本文介绍了将XML代码段插入Groovy中的另一个XML文档中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码段应在elem之后紧接着将片段XML插入主体.
The following code snippet should insert the fragment XML into body, right after elem.
def body = '''
<parent>
<child>
<elem>
<name>Test</name>
</elem>
</child>
</parent>
'''
def fragment = '''
<foo>
<bar>hello!</bar>
<baz/>
</foo>
'''
def bodyNode = new XmlParser().parseText(body)
def fragmentNode = new XmlParser().parseText(fragment)
bodyNode.child*.appendNode(fragmentNode)
def newFileName= '/Users/xxx/out.xml'
def writer = new FileWriter(newFileName)
new XmlNodePrinter(new PrintWriter(writer)).print(bodyNode)
out.xml的预期内容:
Expected content of out.xml:
<parent>
<child>
<elem>
<name>Test</name>
</elem>
<foo>
<bar>hello!</bar>
<baz/>
</foo>
</child>
</parent>
但是我得到的却是:
<parent>
<child>
<elem>
<name>Test</name>
</elem>
<foo/>
</child>
</parent>
如您所见,省略了foo元素的内容.出现这种现象的原因是什么?如何获得正确的输出?
As you can see the content of foo element is omitted. What is the reason for this behavior and how can I achieve the correct output?
推荐答案
原因:
使用appendNode()
而不是append()
.尝试以下方法:
use of appendNode()
instead of append()
. Try this instead:
bodyNode.child*.append(fragmentNode)
或者
这是使用XmlSlurper
获得正确输出的一种方法:
This is one way to achieve the correct output using XmlSlurper
:
def body = '''
<parent>
<child>
<elem>
<name>Test</name>
</elem>
</child>
</parent>
'''
def fragment = '''
<foo>
<bar>hello!</bar>
<baz/>
</foo>
'''
def slurper = new XmlSlurper( false, false, false )
def bodyNode = slurper.parseText( body )
def fragmentNode = slurper.parseText( fragment )
bodyNode.child << fragmentNode
def sw = new StringWriter()
groovy.xml.XmlUtil.serialize(bodyNode, sw)
println sw.toString()
这篇关于将XML代码段插入Groovy中的另一个XML文档中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文