Sunday, May 17, 2015

Reading XML With STAX Event Or Iterator API

STAX Parser is modern parser which is act as pull based parser, means application have control over this parser how and when read the next tag on xml file. It have another advantage that using this parser we can also write a xml file.

STAX is event base xml parser API so it will not load the whole xml file into the memory so we can safe from memory out of bound exception.

STAX API have 2 type.

 1. Event Or Iterator base
 2. Stream Or Cursor base

We will learn here STAX Event or Iterator base API.

Step 1:
  Create and XMLInputFactory instance.
      
        XMLInputFactory xmlFactory=XMLInputFactory.newInstance();

Step 2:
  Create XMLEventReader instance with FileInputStream of input file as argument.
        XMLEventReader xmlEvtReader=xmlFactory.createXMLEventReader("File");
Step 3:
  Iterate the XMLEventReader object  and identify the various elements in the document
       while (xmlEvtReader.hasNext()) {
            XMLEvent evnt = xmlEvtReader.nextEvent();

        }

Step 4:
  After reading the entire document , close the XMLEventReader object.
       xmlEvtReader.close();

Sample Example Code Given Below :


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;


public class STAXEventParserExample {

    public static void main(String[] args) throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
        /**
         * Create XMLInputFactory Factory.
         */

        XMLInputFactory xmlFactory=XMLInputFactory.newInstance();
        /**
         * Create XMLEventReader.
         */

        XMLEventReader xmlEvtReader=xmlFactory.createXMLEventReader(new InputStreamReader(new FileInputStream("c:\\file.xml"), "UTF-8"));
        /**
         * Iterate until last Element in XML.
         */

        while (xmlEvtReader.hasNext()) {
            /**
             * Move To Next XML Element And Check Element Type.
             */

            XMLEvent evnt = xmlEvtReader.nextEvent();
            if(evnt.isStartElement()){
                System.out.println(evnt.asStartElement().getName());
            }
            if(evnt.isEndElement()){
                System.out.println(evnt.asEndElement().getName());
            }
            if(evnt.isCharacters()){
                System.out.println(evnt.asCharacters().getData());
            }
        }
        /**
         * Close XMLEventReader
         */

        xmlEvtReader.close();
    }   
}

No comments:

Post a Comment