问题
I have a problem with the below scenario:
-- 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")
}
)
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>
...
however structure is missing from the result entirely, so I guess there is something wrong with the way I call the outer closure "commonNode()".
Hope someone has an answer. Let me know if you need further details.
回答1:
This works:
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 )
来源:https://stackoverflow.com/questions/19026002/xmlslurper-in-groovy-script-insert-nodes-to-gpathresult-using-external-closu