Home > Groovy, XML > Groovy – Easy XML Parsing with the XmlSlurper

Groovy – Easy XML Parsing with the XmlSlurper


Groovy comes built-in with a cool feature for parsing XML, and easily “objectifying” it.
Its a one-liner:

def document = new XmlSlurper().parseText(xml); // Convert the XML into an Object Model

Usage example

import groovy.util.*;

public class GroovyXmlSlurperExample
{
   public static void main(String[] args)
   {
      def xml = "<root>\n\t<item name=\"a\" value=\"1\"/>\n\t<item name=\"b\" value=\"2\"/>\n</root>";
      System.out.println("XML is: \n" + xml);

      def document = new XmlSlurper().parseText(xml); // Convert the XML into an Object Model

      System.out.println("\nElements are:");
      for (item in document.item)
      {
         System.out.println(item.@name.text() + "=" + item.@value.text());
      }
        
      System.out.println("\nJust the value of the 'value' attributes: " + document."item".@value.text());
   }
}

Explanation

Line #10 – parses the XML from a String to an actual object.
Line #13 – iterates over all the elements of type “item” under the root.
Line #15 – shows how to get the value of attributes for a certain element, the ‘@name’ syntax refers to an attribute named “name” (... name="a" ...)

Further Reading & Experiments

Categories: Groovy, XML Tags: , , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.