xmlgroovybuildermarkupbuilder

How to add nodes under to different parents in Groovy Markup Builder by calling a method or closure


I would like to produce below xml. I do not want to add xsv block inside xpm and MyRoot by repeating the same code.Instead I want to call a method or closure so that It will return xsv block which can be added in the respective parent node(MyRoot and xpm)

<MyRoot>
   <xsv>
      <action>create</action>
      <actionID>4</actionID>
   </xsv>
   <xpm>
      <xsv>
         <action>create</action>
         <actionID>4</actionID>
      </xsv>
   </xpm>
</MyRoot>

Solution

  • Try the following piece of code:

    import groovy.xml.MarkupBuilder
    
    def writer = new StringWriter()
    def builder = new MarkupBuilder(writer)
    def out = builder.MyRoot { 
       addXsv(builder, 'create', 4)
          xpm() {
             addXsv(builder, 'drop', 5)
          }
       }
    
    def addXsv(builder, name, id) {
       builder.xsv() {
          action name
          actionID id
       }
    }
    
    println writer