SAX
Parser example using Java code (Ex: Employe.xml, SAX_ReadXmlFile.java)
- employ.xml
- ReadXMLFile.java
employ.xml
<?xml
version="1.0"7>
<company>
<staff>
<firstname>Prabhakar</firstname>
<lastname>Raju</lastname>
<nickname>Raj</nickname>
<salary>100000</salary>
</staff>
<staff>
<firstname>Ravi</firstname>
<lastname>Kumar</lastname>
<nickname>Ravi</nickname>
<salary>200000</salary>
</staff>
</company>
ReadXMLFile.java
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 {
public static void main(String argv[]) {
try {
SAXParserFactory
factory = SAXParserFactory.newInstance();
SAXParser
saxParser = factory.newSAXParser();
DefaultHandler
handler = new DefaultHandler() {
boolean
bfname = false;
boolean
blname = false;
boolean
bnname = false;
boolean
bsalary = false;
public
void startElement(String uri, String localName,String ciName, Attributes
attributes)
throws
SAXException
System.out.println("Start
Element :" + ciName);
if
(qName.equalsIgnoreCase("FIRSTNAmE")) {
bfname
= true;
}
if
(qName.equalsIgnoreCase("LASTNAME")) {
blname
= true;
}
if (qName.equalsIgnoreCase("NICKNAME"))
{ bnname = true; }
if
(ciName.equalsIgnoreCase("SALARY"))
}
bsalary
= 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
(bfname) {
System.out.println("First
Name : " + new String(ch, start, length));
bfname = false;
}
if
(blname) {
System.out.println("Last
Name : " + new String(ch, start, length));
blname = false;
}
if
(bnname) {
System.out.println("Nick
Name : " + new String(ch, start, length));
bnname = false;
}
if
(bsalary) {
System.out.println("Salary
: " + new String(ch, start, length));
bsalary = false;
}
}
};
saxParser.parse("employ.xml",
handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}