Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Parsing XML in Groovy using XmlSlurper

DZone's Guide to

Parsing XML in Groovy using XmlSlurper

· Java Zone
Free Resource

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

In my previous post I showed different ways in which we can parse XML document in Java. You must have noticed the code being too much verbose. Other JVM languages like GroovyScala provide much better support for parsing XML documents.

In this post I give you the code to parse the XML document in Groovy and one can compare the ease with which we can parse XML documents. I make use of XmlSlurper API in Groovy which loads the complete XML into a tree and this tree can be then navigated using Groovy’s version of XPath called GPath.

The XML document I am using is the same one used here and also the intent is to parse the XML and create a list of Employee object.

class XmlParserDemo {
  static void main(args){
    def empList = new ArrayList<Employee>();
    def emp;
    def employees = 
      new XmlSlurper().parse(ClassLoader.
          getSystemResourceAsStream("xml/employee.xml"));
    employees.employee.each{ node -> 
      emp = new Employee();
      emp.firstName = node.firstName
      emp.lastName = node.lastName
      emp.id = node.@id
      emp.location = node.location
      empList.add(emp)
    }
    empList.each{ empT -> println(empT)}
  }
}
class Employee{
  String firstName
  String lastName
  String id
  String location
   
  @Override
  public String toString(){
    return "${firstName} ${lastName}(${id}) in ${location}"
  }
}

The output is:

Rakesh Mishra(111) in Bangalore
John Davis(112) in Chennai
Rajesh Sharma(113) in Pune

And the XML is present in the “xml” package and is available in the classpath of the application. I am using the ClassLoader to load the XML resource.

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

Topics:

Published at DZone with permission of Mohamed Sanaulla, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}