Codementor Events

XML parsing with Groovy

Published Oct 10, 2020Last updated Sep 12, 2024
XML parsing with Groovy

One of my mentees had this issue with updating an XML file while preserving its original structure, whitespaces, and comments using Groovy. We faced a couple of challenges since XmlParser and XmlSlurper, the popular parsers, are deprecated and didn’t maintain the original XML structure when saving.

To update an XML file while preserving its original structure, whitespaces, and comments in Groovy, we used DOMBuilder and DOMCategory instead of the deprecated XmlParser and XmlSlurper. Here's a minimal example:

import groovy.xml.DOMBuilder
import groovy.xml.dom.DOMCategory

def input = new File('in.xml').text
def doc = DOMBuilder.parse(new StringReader(input))
def meals = doc.documentElement

use(DOMCategory) {
    meals.category[0]['@time'] = '7am'  // Update the breakfast time
}

new File('out.xml').write(meals as String)

For the full tutorial and code snippets, visit https://nadbn.com/2020/10/xml-parsing-with-groovy.html

Discover and read more posts from Nadika Bandara
get started