Archive for the ‘snippet’ Category

[groovy] using XmlSlurper remove, add, append to xml node

2012/08/24

groovy XmlSlurper is very useful!!!

sample.xml

<service>
  <method name="remove">
  </method>
  <method name="add">
    <param name="param1"/>
  </method>
</service>

sample.groovy

def root = new XmlSlurper().parse(new File("sample.xml"));
root.method.each{ mtd ->
  def mtdname = mtd.name.toString()
  // remove node 
  if(mtdname.equals("remove")){ mtd.replaceNode{} }
  // add node
  if(mtdname.equals("add")){ mtd.param + { exception(name:"Exception") } }
  // append node
  mtdname.appendNode{ mtd.method(name: "appendmethod") }
}

result

<service>
  <method name="add">
    <param name="param1"/>
    <exception name="Exception"/>
  </method>
  <method name="appendmethod"/>
</service>