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')
  outputFile.append('</beans>)
}

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",
  [className:"org.springframework.web.struts.ContextLoaderPlugIn"])
// tell the plugin where the Spring bean file will be
pluginNode.appendNode("set-property",
  [property:"contextConfigLocation",value:"action-beans.xml"])
// now add the delegating request processor
Node controllerNode = strutsConfig.appendNode("controller")
controllerNode.appendNode("set-property",[property:"processorClass",
  value:"org.springframework.web.struts.DelegatingRequestProcessor"])
// now write the file out
XmlNodePrinter printer = new XmlNodePrinter(
  new PrintWriter(new File(strutsConfigNew)))
printer.print(strutsConfig)

You can see how easy it is to append nodes and then write the XML back out. For more information, see:

http://groovy.codehaus.org/Processing+XML

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 *

503,438 Spambots Blocked by Simple Comments

HTML tags are not allowed.