--- title: Groovy - Updating XML with XmlSlurper tags: - IT/Development/Groovy --- # Updating XML with XmlSlurper Here is an example of updating XML using XmlSlurper: ```groovy // require(groupId:'xmlunit', artifactId:'xmlunit', version:'1.1')import org.custommonkey.xmlunit.Diff import org.custommonkey.xmlunit.XMLUnit import groovy.xml.StreamingMarkupBuilder def input = ''' Chocolate Coffee Paper Pens Kathryn's Birthday ''' def expectedResult = ''' Iced Tea Pens Mum's Birthday Monica's Birthday Wine ''' def root = new XmlSlurper().parseText(input) // modify groceries: quality items pleasedef groceries = root.category.find{ it.@type == 'groceries' } (0.. p.@quantity = (p.@quantity.toInteger() + 2).toString() p.@when = 'Urgent' } // modify presents: August has come and gonedef presents = root.category.find{ it.@type == 'present' } presents.replaceNode{ node -> category(type:'present'){ item("Mum's Birthday") item("Monica's Birthday", when:'Oct 15') } } // append child at the end of shopping root.appendNode { category { item("Wine") } } // delete all occurrences of a specific element inside a specific parent root.category[0].item.replaceNode {} // update the text of a specific element root.category[1].item[0] = "Iced Tea" // check the whole document using XmlUnitdef outputBuilder = new StreamingMarkupBuilder() String result = outputBuilder.bind{ mkp.yield root } XMLUnit.setIgnoreWhitespace(true) def xmlDiff = new Diff(result, expectedResult) assert xmlDiff.similar() // check the when attributes (can't do before now due to delayed setting)def resultRoot = new XmlSlurper().parseText(result) def removeNulls(list) { list.grep{it} } assert removeNulls(resultRoot.'*'.item.@when) == [ "Urgent", "Oct 15" ] ```