A simple SAX Parser utility
A simple SAX Parser utility
Here i have given a generalised SAX Parser that can parse a given XML url , or a given XML file.
I’ll give the code first , the explanation has been done in the end.
========================================================
/**
* This Class takes the url of the XML file , or the file itself, that is to be parsed and performs setup of the XMLParser Class
* by calling setupConfiguration(). After that, parsing is comenced by calling parseData(URL url_to_be_parsed).
* Actual parsing is performed by the XMLParser class, which stores the results in a HashTable.
*
* In this class we have the getDataForTag(String tag) method , which takes the tag name as input and returns the
* corressponding ArrayList containing the result set for the tag passed as Input parameter.The getDataForTag(String tag)
* performs this operation by calling the getTagContents(String tag) of the XMLParser class from within its method body.
*
* We setup an inner class XMLParser , that actually performs the parsding on the given XML source.
*
*/
package com.example.simpleparser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public class FetchParsedData {
private XMLReader xr;
private XMLParser xparser = new XMLParser();
private InputStream mInpStrm;
//************ constructor ************//
public FetchParsedData(URL url){
try {
setup();
mInpStrm = url.openStream();
parseData(mInpStrm);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//****** alternative constructor, this one takes a file instead of a url……………//
public FetchParsedData(File file){
try {
setup();
FileInputStream mFileInputStream = new FileInputStream(file);
parseData(mFileInputStream);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setup(){
try {
xr = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
xr.setContentHandler(xparser);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Opens an InputStream from the url of the XML file to be parsed , and initiates parsing operation on it.
* @param url => The url of the XML file
*/
private void parseData(InputStream inpstrm){
try {
xr.parse(new InputSource(inpstrm));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* method to retrieve the parsed result tagwise.
* @param tag => the XML tag corressponding to which the values are nedded
* @return => the ArrayList<String> containing the values corressponding the given tag
*/
public ArrayList<String> getDataForTag(String tag){
return xparser.getTagContents(tag);
}
/**
*
* We now define the inner class XMLParser , that perfroms the parsing operation on the given XML . The parser is set on the
* XML file that is to be parsed by the private setup() method of the FetchParsedData class in its constructor.
*
*/
private class XMLParser extends DefaultHandler{
private boolean currentElement = false;
private String currentValue = null;
private Hashtable<String, ArrayList<String» mTagValueMap; // Declare a new HashTable
ArrayList<String> mTempObj; // Stores the values corressponding to a key in the hashmap
/**
* CONSTRUCTOR ; we intialize the HashTable that will hold the parsed data
*/
public XMLParser(){
mTagValueMap = new Hashtable<String, ArrayList<String»();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
/**
* Check if the current tag is already present as a key in our hashtable , if not , then we add the current
* tag as a new key in our hashtable and associate a new ArrayList to is as its value parameter.
*
*/
if (mTagValueMap.containsKey(localName)) {
// if the localName is already present in the HashTable as a key,
// we point the corressponding arraylist to our mTempObj.
mTempObj = mTagValueMap.get(localName);
}
else {
mTempObj = new ArrayList<String>();
mTagValueMap.put(localName, mTempObj);
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
mTempObj.add(currentValue);
} // add the current value into the ArrayList object mapped to the corressponding key parameters
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
}
/**
* @param tagName ; the tag whose contents are sought.
* @return the ArrayList containing the values corressponding to the given tag
*/
public ArrayList<String> getTagContents(String tagName){
return mTagValueMap.get(tagName);
}
}
}
======================================================
Now , by using this class you will be saved the labor of setting you getters and setters to store and retrieve the parsed data.
Also there is no need to hard code the tags that are to be parsed. The code takes care of it on its own.
Now in order to use this class , you have to do the following simple three Steps.
STEP 1: Create an object of the above class by passing the url of the XML .Alternativly you can also pass a local XML file to the constructor.
objFetchParsedData = new FetchParsedData(url_of_XML);
STEP 2: Create an ArrayList to store the contents of a particular tag. The datatype of the ArrayList will be same to the data set returned by the tag.
ArrayList<String> myArrayList = new ArrayList<String>();
STEP 3:
Call the getDataForTag(String tag) method of the FetchParsedData class , this method takes the name of the Tag whose parsed contents are required , and returns the result in the form of ArrayList.
Suppose , our XML contains a “<name>” tag , and we want all the values corresponding to this tag.
so we will call the getDataForTag() method
myArrayList = objFetchParsedData.getDataForTag(name);
here myArrayList is the ArrayList we created in STEP 2 , objFetchParsedData is the FetchParsedData obj we created in STEP 1 , and “name” is one of the tags in our XML.
In summary , all you need to do in order to get values corressponding to a given tag in your XML is this :
FetchParsedData obj = new FetchParsedData(url);
ArrayList<String> alist = new ArrayList<String>();
alist = obj.getDataForTag(“tag_name”);
I hope this simple parser utility helps you in your programming needs, Please feel free to share your comments , criticism and suggestions.




















