How to read XML file in Java Using SAX Parser
In this article, we will learn how to read XML file in java using
SAX parser, or Simple API for XML parser uses callback function (org.xml.sax.helpers.DefaultHandler) to inform clients about the XML document structure.
SAX Parser is faster and uses less memory than DOM parser.
The callback methods are as below:-
startDocument() – This method called at the start of the XML document.endDocument() – This method called at the end of the XML document.startElement() – This method called at the start of a document element.endElement() – This method called at the end of a document element.characters() – This method called with the text contents in between the start and end tags of an XML document element.
Note: In Program, consider changing
Java Program of SAX XML Parser
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?xml version="1.0"?> <contactbook> <employee id="101"> <name>Devil Donald</name> <email>donald.devil@abcd.com</email> <phone>+91 9090909090</phone> </employee> <employee id="201"> <name>Nevil Ray</name> <email>ray.nevil@abcd.com</email> <phone>+1 919191919</phone> </employee> </contactbook> |
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
package com.codenuclear; 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 ReadXMLUsingSAX { public static void main(String args[]) { try { SAXParserFactory spFactory = SAXParserFactory.newInstance(); SAXParser saxParser = spFactory.newSAXParser(); DefaultHandler handler = new DefaultHandler() { boolean boolName = false; boolean boolEmail = false; boolean boolPhone = false; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { System.out.println("START Element :" + qName); if (qName.equalsIgnoreCase("NAME")) { boolName = true; } if (qName.equalsIgnoreCase("EMAIL")) { boolEmail = true; } if (qName.equalsIgnoreCase("PHONE")) { boolPhone = true; } } public void endElement(String uri, String localName, String qName) throws SAXException { System.out.println("END Element :" + qName); } public void characters(char c[], int start, int length) throws SAXException { if (boolName) { System.out.println("Name :- " + new String(c, start, length)); boolName = false; } if (boolEmail) { System.out.println("Email :- " + new String(c, start, length)); boolEmail = false; } if (boolPhone) { System.out.println("Phone :- " + new String(c, start, length)); boolPhone = false; } } }; saxParser.parse("D:\\Files\\contactbook.xml", handler); } catch (Exception e) { e.printStackTrace(); } } } |