Sunday, May 17, 2015

Reading XML With STAX Stream Or Cursor API

STAX Stream or Cursor API is a low level pull based API for parsing XML.Its' need less memory than Event or Iterator API because it does not require to create object for each event.

We need to follow this steps to parse a XML file
Step 1:
    Create XMLInputFactory object
         XMLInputFactory xf=XMLInputFactory.newInstance();

Step 2:
     Create XMLStreamReader object  for the input XML.
          XMLStreamReader xsr=xf.createXMLStreamReader(new InputStreamReader(File));

Step 3:
    Iterate the XMLStreamReader object  and identify the various elements in the document
          while (xsr.hasNext()) {
              int e = xsr.next();

          }

Step 4: 
    After reading the entire document , close the XMLStreamReader object.
         xsr.close(); 

Sample Example Code Given Below :


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class STAXStreamParserExample {

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

        XMLInputFactory xf = XMLInputFactory.newInstance();
        /**
         * Iterate until last Element in XML.
         */

        XMLStreamReader xsr = xf.createXMLStreamReader(new InputStreamReader(new FileInputStream("c:\\file.xml")));
        /**
         * Iterate until last Element in XML.
         */

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

            int e = xsr.next();
            if (e == XMLStreamConstants.START_ELEMENT) {
                System.out.println("StartElement Name :" + xsr.getLocalName());
            }
            if (e == XMLStreamConstants.END_ELEMENT) {
                System.out.println("EndElement Name :" + xsr.getLocalName());
            }
            if (e == XMLStreamConstants.CHARACTERS) {
                System.out.println("Element TextValue :" + xsr.getText());
            }
        }
        /**
         * Close XMLEventReader
         */

        xsr.close();
    }
}

 

No comments:

Post a Comment