Convert XML document to Java Object using StAX Cursor API

The StAX Cursor API allows us to parse XML documents to Java objects.

The Cursor API provides XMLStreamReader class parsing XML.

This class is provided in javax.xml.stream package.
 
convert xml to java object
 

Steps for converting JAVA objects to XML document

 
Here are the steps for converting JAVA objects to XML document :

– Create an XMLInputFactory

– Create a FileInputStream

– Create an XMLStreamReader using the XMLInputFactory and FileInputStream

– Use the XMLStreamReader’s methods to parse the XML document and create Java object.
 

Example code

 
We will parse a xml file (C:\stax\Devices.xml) file to get Device information using StAX api:
 

<?xml version="1.0" ?>
<devices>
  <device>
    <name>iPhone</name>
    <model>6s</model>
  </device>
  <device>
    <name>iPhone</name>
    <model>7</model>
  </device>
  <device>
    <name>iPad</name>
    <model>2</model>
  </device>
</devices>

 
We will populate following Device POJO objects from the above XML file.
 
package com.topjavatutorial.stax;

public class Device {
  String name;
  String model;

  public Device(){
    
  }
  
  public Device(String name, String model) {
    this.name = name;
    this.model = model;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getModel() {
    return model;
  }

  public void setModel(String model) {
    this.model = model;
  }

}


 
Here is the code for parsing device.xml file using XMLStreamReader class and populating Device objects.
 
package com.topjavatutorial.stax;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class XMLReader {
  private static boolean isName = false;
  private static boolean isModel = false;
  static String text="";
  public static void main(String[] args) {
    String xmlFile = "C:\\stax\\Devices.xml";
    List<Device> deviceList = parseXML(xmlFile);
    for(Device d : deviceList){
      System.out.println("Device Name : " + d.getName() + ", Model : " + d.getModel());
    }
  }

  private static List<Device> parseXML(String xmlFile){
    List<Device> deviceList=null;
    Device dev = null;
    XMLInputFactory factory = XMLInputFactory.newFactory();
    try (FileInputStream fis = new FileInputStream(xmlFile);) {
      XMLStreamReader reader = factory.createXMLStreamReader(fis);

      while (reader.hasNext()) {
        switch (reader.getEventType()) {
        case XMLStreamConstants.START_ELEMENT:
          String elementName = reader.getLocalName();
          switch(elementName){
          case "devices":
            deviceList = new ArrayList<>();
            break;
          case "device":
            dev = new Device();
            break;
          case "name":
            isName = true;
            break;
          case "model":
            isModel = true;
            break;
          default:
            break;
          }
          break;
        case XMLStreamConstants.CHARACTERS:
          if(isName){
            dev.setName(reader.getText());
            isName = false;
          }
          else if(isModel){
            dev.setModel(reader.getText());
            isModel = false;
          }
          if(reader.hasText())
            text = reader.getText();
          break;
        case XMLStreamConstants.END_ELEMENT:
          elementName = reader.getLocalName();
          if(elementName.equals("device"))
            deviceList.add(dev);
          break;

        case XMLStreamConstants.START_DOCUMENT:
          deviceList = new ArrayList<>();
                break;
        }

        reader.next();
      }
      reader.close();
    } catch (IOException | XMLStreamException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return deviceList;
  }
}

 

Output

 
Device Name : iPhone, Model : 6s
Device Name : iPhone, Model : 7
Device Name : iPad, Model : 2

 

You may also like :

Convert Java Object to XML using StAX api

String to XML and XML to String in Java

Converting XML Schema to Java object and vice versa using schemagen and xjc

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags