In java We can parse an XML file two ways.First is SAX parser and Second is DOM parser but here I am using SAX parser.
SAX means Simple API for XML .This developed into the SAX Project by David Megginson before finally being added to Java Standard Edition 1.4.
SAX parser is the most commonly used xml parser in Java after DOM, unlike DOM Sax does not loads the XML into memory before parsing it, nor it creates any type of object from XML. SAX is a better choice to parse xml's with large size. SAX uses some callback methods
to parse and read the xml accordingly. It uses four callback methods listed below :
Note: SAX Parser is faster and uses less memory than DOM parser.
Below are SAX callback methods :
startDocument() and endDocument(): Method called at the start and end of an XML document.
startElement(): Every time a SAX parser gets a opening tag '<', it calls startElement() and
process the xml according to the code written in startElement().
endElement() : Every time a SAX parser gets a closing tag '>', it calls endElement() and
process the xml according to the code written in endElement().
characters() : Every time a SAX parser gets a simple character string, it calls character()
method and the xml according to the code written in startElement().
For Example:
Here is the sample xml document that we are going to parse and write the content using System.out.ptinln().
Save as employee.xml
<?xml version="1.0" encoding="UTF-8"?>
<company>
<employee id="1">
<firstname>vishwa</firstname>
<lastname>singh</lastname>
<email>vishwasingh@gmail.com</email>
<phone>7411909624</phone>
</employee>
<employee id="2">
<firstname>aakash</firstname>
<lastname>singh</lastname>
<email>aakashsingh@gmail.com</email>
<phone>955712635</phone>
</employee>
</company>
Below class shows actual implementation of sax parser in java, see the code below to understand how to use sax in xml parser:
Save as ParseXml.java
package com.vishwa;
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 ParseXml extends DefaultHandler{
public void getXml(){
try {
// obtain and configure a SAX based parser
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
// obtain object for SAX parser
SAXParser saxParser = saxParserFactory.newSAXParser();
// default handler for SAX handler class
// all three methods are written in handler's body
DefaultHandler defaultHandler = new DefaultHandler(){
String firstNameTag=false;
String lastNameTag=false;
String emailTag=false;
String phoneTag=false;
// this method is called every time the parser gets an open tag '<'
// identifies which tag is being open at time by assigning an open flag
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("firstname")) {
firstNameTag = true;
}
if (qName.equalsIgnoreCase("lastname")) {
lastNameTag = true;
}
if (qName.equalsIgnoreCase("email")) {
emailTag = true;
}
if (qName.equalsIgnoreCase("phone")) {
phoneTag = true;
}
}
// prints data stored in between '<' and '>' tags
public void characters(char ch[], int start, int length)
throws SAXException {
if (firstNameTag) {
System.out.println("First Name : " + new String(ch, start, length));
}
if (lastNameTag) {
System.out.println("Last Name : " + new String(ch, start, length));
}
if (emailTag) {
System.out.println("Email : " + new String(ch, start, length));
}
if (phoneTag) {
System.out.println("Phone : " + new String(ch, start, length));
}
}
// calls by the parser whenever '>' end tag is found in xml
// makes tags flag to false
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("firstName")) {
firstNameTag = false;
}
if (qName.equalsIgnoreCase("lastName")) {
lastNameTag = false;
}
if (qName.equalsIgnoreCase("email")) {
emailTag = "false;
}
if (qName.equalsIgnoreCase("phone")) {
phoneTag = "false;
}
}
};
// parse the XML specified in the given path and uses supplied
// handler to parse the document
// this calls startElement(), endElement() and character() methods accordingly
saxParser.parse("xmlFileLocation/employee.xml", defaultHandler);
} catch (Exception e) {
e.printStackTrace();
}
} // end of getXml() method
} // end of class
Implementation class code:
This is a simple implementation class to see the things working.
Save as SaxParserImplementation.java
package com.vishwa;
public class SaxParserImplementation {
public static void main(String args[]){
ParseXml parseXml = new ParseXml();
parseXml.getXml();
}
}
Output:
First Name: vishwa
Last Name: singh
Email: vishwasingh@gmail.com
Phone: 7411909624
First Name: aakash
Last Name: singh
Email: aakashsingh@gmail.com
Phone: 9555712635
In this particular blog we cam across 'How to read xml in java using sax parser' and 'how to
use sax for xml parsing'. In upcoming blogs we will come across more about more xml parser(DOM) in java and their implementation.
SAX means Simple API for XML .This developed into the SAX Project by David Megginson before finally being added to Java Standard Edition 1.4.
SAX parser is the most commonly used xml parser in Java after DOM, unlike DOM Sax does not loads the XML into memory before parsing it, nor it creates any type of object from XML. SAX is a better choice to parse xml's with large size. SAX uses some callback methods
to parse and read the xml accordingly. It uses four callback methods listed below :
Note: SAX Parser is faster and uses less memory than DOM parser.
Below are SAX callback methods :
startDocument() and endDocument(): Method called at the start and end of an XML document.
startElement(): Every time a SAX parser gets a opening tag '<', it calls startElement() and
process the xml according to the code written in startElement().
endElement() : Every time a SAX parser gets a closing tag '>', it calls endElement() and
process the xml according to the code written in endElement().
characters() : Every time a SAX parser gets a simple character string, it calls character()
method and the xml according to the code written in startElement().
For Example:
Here is the sample xml document that we are going to parse and write the content using System.out.ptinln().
Save as employee.xml
<?xml version="1.0" encoding="UTF-8"?>
<company>
<employee id="1">
<firstname>vishwa</firstname>
<lastname>singh</lastname>
<email>vishwasingh@gmail.com</email>
<phone>7411909624</phone>
</employee>
<employee id="2">
<firstname>aakash</firstname>
<lastname>singh</lastname>
<email>aakashsingh@gmail.com</email>
<phone>955712635</phone>
</employee>
</company>
Below class shows actual implementation of sax parser in java, see the code below to understand how to use sax in xml parser:
Save as ParseXml.java
package com.vishwa;
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 ParseXml extends DefaultHandler{
public void getXml(){
try {
// obtain and configure a SAX based parser
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
// obtain object for SAX parser
SAXParser saxParser = saxParserFactory.newSAXParser();
// default handler for SAX handler class
// all three methods are written in handler's body
DefaultHandler defaultHandler = new DefaultHandler(){
String firstNameTag=false;
String lastNameTag=false;
String emailTag=false;
String phoneTag=false;
// this method is called every time the parser gets an open tag '<'
// identifies which tag is being open at time by assigning an open flag
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("firstname")) {
firstNameTag = true;
}
if (qName.equalsIgnoreCase("lastname")) {
lastNameTag = true;
}
if (qName.equalsIgnoreCase("email")) {
emailTag = true;
}
if (qName.equalsIgnoreCase("phone")) {
phoneTag = true;
}
}
// prints data stored in between '<' and '>' tags
public void characters(char ch[], int start, int length)
throws SAXException {
if (firstNameTag) {
System.out.println("First Name : " + new String(ch, start, length));
}
if (lastNameTag) {
System.out.println("Last Name : " + new String(ch, start, length));
}
if (emailTag) {
System.out.println("Email : " + new String(ch, start, length));
}
if (phoneTag) {
System.out.println("Phone : " + new String(ch, start, length));
}
}
// calls by the parser whenever '>' end tag is found in xml
// makes tags flag to false
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("firstName")) {
firstNameTag = false;
}
if (qName.equalsIgnoreCase("lastName")) {
lastNameTag = false;
}
if (qName.equalsIgnoreCase("email")) {
emailTag = "false;
}
if (qName.equalsIgnoreCase("phone")) {
phoneTag = "false;
}
}
};
// parse the XML specified in the given path and uses supplied
// handler to parse the document
// this calls startElement(), endElement() and character() methods accordingly
saxParser.parse("xmlFileLocation/employee.xml", defaultHandler);
} catch (Exception e) {
e.printStackTrace();
}
} // end of getXml() method
} // end of class
Implementation class code:
This is a simple implementation class to see the things working.
Save as SaxParserImplementation.java
package com.vishwa;
public class SaxParserImplementation {
public static void main(String args[]){
ParseXml parseXml = new ParseXml();
parseXml.getXml();
}
}
Output:
First Name: vishwa
Last Name: singh
Email: vishwasingh@gmail.com
Phone: 7411909624
First Name: aakash
Last Name: singh
Email: aakashsingh@gmail.com
Phone: 9555712635
In this particular blog we cam across 'How to read xml in java using sax parser' and 'how to
use sax for xml parsing'. In upcoming blogs we will come across more about more xml parser(DOM) in java and their implementation.
No comments:
Post a Comment