Blog Archive

Monday, June 26, 2017

Groovy xml parsing example

Om


import org.custommonkey.xmlunit.*
import groovy.xml.*


def todo = new XmlSlurper().parseText(xml)

// Change node values.
def items = todo.roo1.item.findAll {
  it.@priority.toInteger() < 3
}
items.each { item ->
   item.title = "DO: " + item.title
}


// Change attribute value.
def gpars= todo.root1.item.find {
   it.title =~ /.*GPars.*/
}
gpars.@priority = '1'
// Add extra item node.
todo.root1.appendNode {
   item(priority: 2) {
  title 'Work on blog post'
   }}
// Change node.
def grailsItem = todo.root1.item.find {
   it.title.toString().contains('Grails')
}
grailsItem.replaceNode { node ->
   item(who: 'mrhaki', priority: node.@priority) {
  title 'Download Grails 1.4 M1' }}
   


// Remove node. Index value based on result directly after parsing.
// So here we remove the item about GWT.
todo.root1.item[3].replaceNode {}

// Create output.
def newTodo = new StreamingMarkupBuilder().bind {
   mkp.yield todo
}.toString()


println XmlUtil.serialize( newTodo)
//XMLUtil.ignoreWhitespace = true
//def difference = new Diff(newTodo, expected)
//assert difference.similar()

No comments:

Post a Comment