Skip to: Site menu | Main content

Groovy 

      Download | Documentation | Developers | Community

An agile dynamic language for the Java Platform

Updating XML with DOMCategory Add comment to Wiki View in Wiki Edit Wiki page Printable Version

Here is an example of updating XML using DOMCategory:

// require(groupId:'xmlunit', artifactId:'xmlunit', version:'1.1')
import groovy.xml.dom.DOMUtil
import groovy.xml.dom.DOMCategory
import groovy.xml.DOMBuilder
import org.custommonkey.xmlunit.Diff
import org.custommonkey.xmlunit.XMLUnit

def input = '''
<shopping>
    <category type="groceries">
        <item>Chocolate</item>
        <item>Coffee</item>
    </category>
    <category type="supplies">
        <item>Paper</item>
        <item quantity="4">Pens</item>
    </category>
    <category type="present">
        <item when="Aug 10">Kathryn's Birthday</item>
    </category>
</shopping>
'''

def expectedResult = '''
<shopping>
  <category type="groceries">
    <item>Luxury Chocolate</item>
    <item>Luxury Coffee</item>
  </category>
  <category type="supplies">
    <item>Paper</item>
    <item quantity="6" when="Urgent">Pens</item>
  </category>
  <category type="present">
    <item>Mum's Birthday</item>
    <item when="Oct 15">Monica's Birthday</item>
  </category>
</shopping>
'''

def reader  = new StringReader(input)
def doc     = DOMBuilder.parse(reader)
def root    = doc.documentElement

use(DOMCategory) {
    // modify groceries: quality items please
    def groceries = root.category.findAll{ it.'@type' == 'groceries' }[0].item
    groceries.each { g ->
        g.value = 'Luxury ' + g.text()
    }

    // modify supplies: we need extra pens
    def supplies = root.category.findAll{ it.'@type' == 'supplies' }[0].item
    supplies.findAll{ it.text() == 'Pens' }.each { s ->
        s['@quantity'] = s.'@quantity'.toInteger() + 2
        s['@when'] = 'Urgent'
    }

    // modify presents: August has come and gone
    def presents = root.category.find{ it.'@type' == 'present' }
    presents.item.each {
        presents.removeChild(it)
    }
    presents.appendNode('item', "Mum's Birthday")
    presents.appendNode('item', [when:'Oct 15'], "Monica's Birthday")

    // check the when attributes
    assert root.'**'.item.'@when'.grep{it} == ["Urgent", "Oct 15"]
}

// check the whole document using XmlUnit
XMLUnit.setIgnoreWhitespace(true)
def result = DOMUtil.serialize(root)
def xmlDiff = new Diff(result, expectedResult)
assert xmlDiff.identical()