Ad

Wednesday 18 June 2014

Parsing XML using stax parser in Java

STAX API uses the pull parsing methodology,where we call the methods on the Stax Library and depending on the events returned we get the values from the XML.When parsing using STAX,it will return the different events depending on the XML element type which it is current referring to.

Lets say we want to parse the below XML and we need to set the values in the Employee object.

employee.xml

<?xml version="1.0" encoding="UTF-8"?>                                                                                        
<employeedetails>
  <employee id="1">
<name>Rahul</name>
<age>25</age>
               <department>IT</department>
    </employee>
    <employee id="2">
<name>John</name>
<age>26</age>
               <department>IT</department>
    </employee>
    <employee id="3">
<name>Peter</name>
<age>29</age>
                <department>HR</department>
    </employee>
</employeedetails>

Employee.java

public class Employee {

private String empId=null;                                                                                                          
private String empName=null;
private String age=null;
private String department=null;

/**
* @return the empId
*/
public String getEmpId() {
return empId;
}

/**
* @param empId the empId to set
*/
public void setEmpId(String empId) {
this.empId = empId;
}

/**
* @return the empName
*/
public String getEmpName() {
return empName;
}

/**
* @param empName the empName to set
*/
public void setEmpName(String empName) {
this.empName = empName;
}

/**
* @return the age
*/
public String getAge() {
return age;
}

/**
* @param age the age to set
*/
public void setAge(String age) {
this.age = age;
}

/**
* @return the department
*/
public String getDepartment() {
return department;
}

/**
* @param department the department to set
*/
public void setDepartment(String department) {
this.department = department;
}

@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + ", age="
+ age + ", department=" + department + "]";
}
}



Below is the sample code for parsing the employee.xml and to set the value in list of employee object.

import java.io.InputStream;  
import java.util.ArrayList;
import java.util.List;
                                                                                                                                                             
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
                                                                                                                                                               
public class StaxExample {

public static void main(String[] args) {
      List<Employee> employeeList=null;
      Employee employee=null;
      try
      {
      XMLInputFactory inputFactory= XMLInputFactory.newFactory();
      InputStream inputStream=StaxExample.class.getClassLoader().
                                                 getResourceAsStream("employee.xml");
      XMLStreamReader xmlStreamReader=inputFactory.createXMLStreamReader(inputStream);
      String elementName="";
      while(xmlStreamReader.hasNext())
      {
     int event=xmlStreamReader.next();
     if(event==XMLStreamConstants.START_ELEMENT)
     {
     elementName=xmlStreamReader.getLocalName();
     if("employeedetails".equalsIgnoreCase(elementName))
     {
     employeeList=new ArrayList<Employee>();
     }
     else if("employee".equalsIgnoreCase(elementName))
     {  
     employee=new Employee();
     if(xmlStreamReader.getAttributeCount()>0 && 
     ("id").equalsIgnoreCase(xmlStreamReader.getAttributeLocalName(0)))
     employee.setEmpId(xmlStreamReader.getAttributeValue(0));
     }
     }
     else if(event==XMLStreamConstants.CHARACTERS)
     {
     String value=xmlStreamReader.getText();
     if(elementName.equalsIgnoreCase("name"))
     {
     employee.setEmpName(value);
     }
     else if(elementName.equalsIgnoreCase("age"))
     {
     employee.setAge(value);
     }
     else if(elementName.equalsIgnoreCase("department"))
     {
     employee.setDepartment(value);
     }
     }
     else if(event==XMLStreamConstants.END_ELEMENT)
     {
     elementName=xmlStreamReader.getLocalName();
     if("employee".equalsIgnoreCase(elementName))
     {
     employeeList.add(employee);
     }
     elementName="";//Reset the elementName(TagName)
     }
      }
      System.out.println("Values Parsed from XML is:"+employeeList.toString());
      }
      catch(Exception e)
      {
     e.printStackTrace();
      }
  }
}

  • The starting point of using STAX API is to get the XMLInputFactory Object.
  • Then we get the XMLStreamReader from this factory by passing the inputstream for the xml to be parsed.Make sure the employee.xml is in the classpath.
  • XMLStreamReader behaves as the pointer to the xml and when we invoke the next() method ,it will return the event of the Current xml element type and moves to next element in the xml.
  • When the start element of any xml tag is reached,it will return the event XMLStreamConstants.START_ELEMENT.Then by using the getLocalName() method we can get the name of the xml tag.To get the value of the attribute in the current element, we can use the method getAttributeValue(index),where index is the position of the attribute in in the corresponding tag
  • When the end element of any xml tag is reached,it will return the event XMLStreamConstants.END_ELEMENT
  • when the value of any tag is reached,it will return the event XMLStreamConstants.CHARACTERS and we can use the method getText() to get the value enclosed within the tag
OUTPUT


Values Parsed from XML is:[Employee [empId=1, empName=Rahul, age=25, department=IT],   Employee [empId=2, empName=John, age=26, department=IT], Employee [empId=3, empName=Peter, age=29, department=HR]]                                                                                     

No comments:

Post a Comment