简体   繁体   English

如何通过调用方法或闭包在Groovy Markup Builder中将节点添加到不同的父节点下

[英]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. 我想生成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) 我不想通过重复相同的代码在xpm和MyRoot中添加xsv块。相反,我想调用一个方法或闭包,这样它将返回xsv块,可以在相应的父节点中添加(MyRoot和xpm)

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM