XmlSlurper in Groovy Script — Insert nodes to GpathResult using external closures

跟風遠走 提交于 2019-12-11 18:02:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!