以下代码片段应将片段XML插入到body中,紧接在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的预期内容:
<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元素的内容被省略。这种行为的原因是什么?如何才能获得正确的输出?
答案 0 :(得分:3)
<强>原因强>:
使用appendNode()
代替append()
。试试这个:
bodyNode.child*.append(fragmentNode)
<强>替代地强>
这是使用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()
答案 1 :(得分:2)
使用XmlParser
的工作示例:
import groovy.xml.XmlUtil
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[0].children().add(fragmentNode)
println(XmlUtil.serialize(bodyNode))