Labels

Sunday, 10 November 2013

Read XML File using SAX Parser


In this tutorial we are going to see how to read XML file using SAX parser.
1. Create Project Called JavaXML.
2. Create package called com.javatutorialscorner.xml.sax under JavaXML.
3. Create Java class called ReadXMLFile.java under com.javatutorialscorner.xml.sax package.
ReadXMLFile.java
package com.javatutorialscorner.xml.sax;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ReadXMLFile {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

try {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser parser = saxParserFactory.newSAXParser();
DefaultHandler defaultHandler = new DefaultHandler() {
boolean firstName = false;
boolean lastName = false;

public void startElement(String uri, String localName,
String qName, Attributes attribute) throws SAXException {
System.out.println("Start Element : " + qName);
if (qName.equalsIgnoreCase("FIRSTNAME")) {
firstName = true;
}
if (qName.equalsIgnoreCase("LASTNAME")) {
lastName = true;
}
}

public void endElement(String uri, String localName,
String qName) throws SAXException {
System.out.println("End Element : " + qName);
}

public void characters(char ch[], int start, int length)
throws SAXException {
if (firstName) {
System.out.println("First Name : "
+ new String(ch, start, length));
firstName = false;
}
if (lastName) {
System.out.println("Last Name : "
+ new String(ch, start, length));
lastName = false;
}
}
};
parser.parse(new File("C:\\jtc\\student.xml"), defaultHandler);
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

student.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<college>
<student>
<firstname>Sathish</firstname>
<lastname>J</lastname>
</student>
</college>

Now you can run the program see the following output in console.

Start Element : college

Start Element : student

Start Element : firstname

First Name : Sathish

End Element : firstname

Start Element : lastname

Last Name : J

End Element : lastname

End Element : student

End Element : college

0 comments

Post a Comment