0

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.

Shinoko
  • 3
  • 1
  • 2

1 Answers1

2

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 )
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • Prompt and useful answer. I just have one additional curiosity: Is there a functional difference between my syntax and yours: child("childvalue") compared to child "childValue"? – Shinoko Sep 26 '13 at 11:30
  • @Shinoko no, it's the same thing :-) Parentheses in this situation are optional :-) – tim_yates Sep 26 '13 at 11:40
  • Is it possible to have a parameter as well? In example the value of child node ("childValue") to be sent as a string when calling the closure. What code changes are required? – Shinoko Sep 27 '13 at 06:32