Groovy脚本中的XmlSlurper ---使用外部闭包将节点插入到GpathResult [英] XmlSlurper in Groovy Script --- Insert nodes to GpathResult using external closures
问题描述
我有一个问题与下面的情况:
I have a problem with the below scenario:
- 我有一个GPathResultbody,我想追加一些更多的xml(节点和子)
- 一些部分是常见的,所以我试图让它们保存在外部闭包commonNode我可以插入任何我需要
-- I have a GPathResult "body" to which I want to append some more xml (nodes and children) -- Some parts are common so I am trying to have them kept in an outer closure "commonNode" I can insert wherever I need
// some more code here to get body
def commonNode = {
return {
node2() {
child("childValue")
}
}
}
body.appendNode(
{
node1("value1")
commonNode()
node3("value3")
}
)
想要得到后我会调用XmlUtil.serialize(body)是这样:
What I want to get after I would call XmlUtil.serialize(body) is this:
...
<body>
<node1>value</node1>
<node2>
<child>childValue</child>
</node2>
<node3>value3</node3>
<body>
...
但是结果完全缺少结果,所以我猜我的外部闭包commonNode()的方式错了。
however structure is missing from the result entirely, so I guess there is something wrong with the way I call the outer closure "commonNode()".
希望有人有答案。
推荐答案
这个工作原理:
import groovy.xml.*
def xml = '<body/>'
def body = new XmlSlurper().parseText( xml )
def commonNode = {
node2 {
child "childValue"
}
}
body.appendNode {
node1 "value1"
commonNode.delegate = delegate
commonNode()
node3 "value3"
}
println XmlUtil.serialize( body )
这篇关于Groovy脚本中的XmlSlurper ---使用外部闭包将节点插入到GpathResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!