Cool Groovy features 6 – XML parsing

Groovy offers a number of features to make XML processing easier:
  • Building XML using a concise syntax and the MarkupBuilder class.
  • XMLSlurper – allows you to read XML and use GPath, similar to XPath, to query the document.
  • XMLParser – allows you to read XML in as Nodes.
Here is an example of reading a file in using XMLSlurper and writing a second file based on it (it is an example of work that might need to be done for migrating from Struts MVC to Spring):
// read the struts file in as XML
GPathResult strutsConfig = new XmlSlurper().parse(inputFile)
// get all of the "action" nodes by traversing from the top level node
def actions = strutsConfig."action-mappings".action

actions.each{ action ->
  outputFile.append('<bean name="' + action.@path + '"n')
  outputFile.append('    class="' + action.@type + '"n')
This code shows how you can use the GPath dot notation to navigate from one node to the next. XmlParser parses documents into nodes and allows you to change the XML:
Node strutsConfig = new XmlParser().parse(inputFile)
// add the Spring context loader plugin.
Node pluginNode = new Node(strutsConfig,"plug-in",
// tell the plugin where the Spring bean file will be
// now add the delegating request processor
Node controllerNode = strutsConfig.appendNode("controller")
// now write the file out
XmlNodePrinter printer = new XmlNodePrinter(
  new PrintWriter(new File(strutsConfigNew)))
You can see how easy it is to append nodes and then write the XML back out. For more information, see:
This entry was posted in Groovy and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

HTML tags are not allowed.

517,234 Spambots Blocked by Simple Comments