Saturday, May 23, 2015

Unknown XML Parsing With STAX

On our last discussion we can now say that we know how to parse a XML file using STAX parser.Now here we try to parse a XML file with unknown structure.It has similar logic which we use in SAX parser to parse a unknown XML.We get the text when Starting Element and End Element name matched.

Code is Given Below For Both Type Of STAX Parser :

Event Or Iterator STAX
----------------------------------------------------------------------------------------------


package STAXParser;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.XMLEvent;

public class STAXEventParserExample {

    public static void main(String[] args) throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
        String startElement = null;
        String endElement = null;
        String elementTxt = null;
        Map<String, String> tmpAtrb = null;
        /**
         * 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()) {
                tmpAtrb=new HashMap();
                startElement = evnt.asStartElement().getName().getLocalPart();
                for (Iterator<Attribute> iterator = evnt.asStartElement().getAttributes(); iterator.hasNext();) {
                    Attribute attribute = iterator.next();
                    String aname = attribute.getName().getLocalPart();
                    String value = attribute.getValue();
                    tmpAtrb.put(aname, value);
                }
            }
            if (evnt.isEndElement()) {
                endElement = evnt.asEndElement().getName().toString();
                if (startElement.equalsIgnoreCase(endElement)) {
                    System.out.println(" ElementName : " + startElement + " ElementText : " + elementTxt);
                    for (Map.Entry<String, String> entrySet : tmpAtrb.entrySet()) {
                        System.out.println(" Attribute Name :" + entrySet.getKey() + " Attribute Value :" + entrySet.getValue());
                    }
                }
            }
            if (evnt.isCharacters()) {
                elementTxt = (evnt.asCharacters().getData().contains("\n")) ? "" : evnt.asCharacters().getData();
            }
        }
        /**
         * Close XMLEventReader
         */

        xmlEvtReader.close();
    }
}
 

Stream Or Cursor STAX
----------------------------------------------------------------------------------------------
package STAXParser;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
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 {
        String startElement = null;
        String endElement = null;
        String elementTxt = null;
        Map<String, String> tmpAtrb = null;
        /**
         * Create XMLInputFactory Factory.
         */

        XMLInputFactory xf = XMLInputFactory.newInstance();
        /**
         * Create XMLStreamReader.
         */

        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) {
                startElement = xsr.getLocalName();
                tmpAtrb = new HashMap();
                for (int i = 0; i < xsr.getAttributeCount(); i++) {
                    String aname = xsr.getAttributeLocalName(i);
                    String value = xsr.getAttributeValue(i);
                    tmpAtrb.put(aname, value);
                }
            }

            if (e == XMLStreamConstants.END_ELEMENT) {
                endElement = xsr.getLocalName();
                if (startElement.equalsIgnoreCase(endElement)) {
                    System.out.println(" ElementName : " + startElement + " ElementText : " + elementTxt);
                    for (Map.Entry<String, String> entrySet : tmpAtrb.entrySet()) {
                        System.out.println(" Attribute Name :" + entrySet.getKey() + " Attribute Value :" + entrySet.getValue());
                    }
                }
            }
            if (e == XMLStreamConstants.CHARACTERS) {
                elementTxt = (xsr.getText().contains("\n")) ? "" : xsr.getText();
            }
        }
        /**
         * Close XMLEventReader
         */

        xsr.close();
    }
}
 


No comments:

Post a Comment