Sunday, November 13, 2011

SAX Parser Example in JAVA


package com.test;
import java.io.StringReader;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


public class ParseXMLUsingSAX {
public static String xmlString = "<?xml version='1.0'?><EMPLOYEE><USER_ID>admin</USER_ID><PASSWORD>admin123</PASSWORD></EMPLOYEE>";
public static void main(String argv[]) {
String fileName = "D:\\test.xml";
parseXml(fileName);
}
public static void parseXml(String fileName){
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlString));
DefaultHandler handler = new DefaultHandler() {
boolean userID = false;
boolean password = false;
public void startElement(String uri, String localName, 
String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("USER_ID")) {
userID = true;
}
if (qName.equalsIgnoreCase("PASSWORD")) {
password = true;
}
}
public void endElement(String uri, String localName,
String qName) throws SAXException {
}
public void characters(char ch[], int start, int length) throws SAXException {
if (userID) {
System.out.println("userID : " + new String(ch, start, length));
userID = false;
}
if (password) {
System.out.println("password : " + new String(ch, start, length));
password = false;
}
}
};
//saxParser.parse(fileName, handler);
saxParser.parse(is, handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}

No comments: