Archive

Posts Tagged ‘groovy’

Groovy – Easy XML Parsing with the XmlSlurper

August 4, 2014 Leave a comment

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

  • Experiment online – just fork this code and play around: https://ideone.com/g2C7Tx
  • Groovy’s tutorial for XML Slurper
  • XmlSlurper “GroovyDoc” page
    • Advertisements
Categories: Groovy, XML Tags: , , , , ,
%d bloggers like this: