Step By Step guide to Read XML file in Java Using SAX Parser Example
2013-11-16 13:38
736 查看
Reading XML file in java using SAX Parser is little different thanreading xml file in Java with DOM parser
which we had discussed in last article of this series. Thistutorial is can be useful for those who are new to the java world and got the requirement forread
an xml file in java in their project or assignment, key feature of java is it provides built in class and object tohandle everything which makes our task
very easy. Basically this process of handling XML file is known asparsing means break down the whole string into small pieces using the special tokens.
Parsing can be done using two ways:
Using DOM Parser
Using SAX Parser
Ø Parse the XML file
Ø Create the java object
Ø Manipulate the object means we can read that object or add them to list or whatever function we want we can do
But in SAX Parser its little bit different.
SAX
Parser: it’s an event based parsing it contains default handler for handling the events whenever SAX parser pareses the xml document and it finds theStart tag “<” and end tag”>”
it calls corresponding handler method.
Though there are other ways also to get data from xml file e.g. using
XPATH in Java which is a language like SQL and give selective data from xml file.
details of all accounts in a hypothetical bank:
<?xmlversion="1.0"encoding="UTF-8"?>
<Bank>
<Accounttype="saving">
<Id>1001</Id>
<Name>Jack Robinson</Name>
<Amt>10000</Amt>
</Account>
<Accounttype="current">
<Id>1002</Id>
<Name>Sony Corporation</Name>
<Amt>1000000</Amt>
</Account>
</Bank>
1. Create the SAX parser and parse the XML file: In this step we will take one factory instance fromSAXParserFactory
to parse the xml file this factory instance in turns give us instance of parser using theparse() method will parse the Xml file.
2. Event Handling: when Sax Parser starts the parsing whenever it founds thestart or end tag it will invoke the corresponding event handling
method which ispublic void startElement (…) and public void end Element (...).
3. Register the events: The class extends the Default Handler class tolisten for callback events and we register this handler to sax Parser
to notify us for call back event
Let see java code for all these steps
To represent data from our sample xml file we need one java domain object called Account:
package parser;
publicclass Account {
private Stringname;
privateintid;
privateintamt;
private Stringtype;
public Account() {
}
public Account(String name,int id,int
amt, String type) {
this.name = name;
this.amt = amt;
this.id = id;
this.type = type;
}
publicint getAmt() {
returnamt;
}
publicvoid setAmt(int amt)
{
this.amt = amt;
}
publicint getId() {
returnid;
}
publicvoidsetId(int
id) {
this.id = id;
}
public String getName() {
returnname;
}
publicvoid setName(String name) {
this.name = name;
}
public String getType() {
returntype;
}
publicvoid setType(String type) {
this.type = type;
}
public String toString() {
StringBuffer sb =
new StringBuffer();
sb.append("Account Details - ");
sb.append("Name:" + getName());
sb.append(", ");
sb.append("Type:" + getType());
sb.append(", ");
sb.append("Id:" + getId());
sb.append(", ");
sb.append("Age:" + getAmt());
sb.append(".");
return sb.toString();
}
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
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;
publicclass ReadXMLFileUsingSaxparserextends
DefaultHandler {
private Accountacct;
private Stringtemp;
private ArrayList<Account>accList =
new ArrayList<Account>();
/** The
main method sets things up for parsing */
publicstaticvoid main(String[] args)throws
IOException, SAXException,
ParserConfigurationException {
//Create a "parser factory" for creating SAX parsers
SAXParserFactory spfac = SAXParserFactory.newInstance();
//Now use the parser factory to create a SAXParser object
SAXParser sp = spfac.newSAXParser();
//Create an instance of this class; it defines all the handler methods
ReadXMLFileUsingSaxparser handler =new ReadXMLFileUsingSaxparser();
//Finally, tell the parser to parse the input and notify the handler
sp.parse("bank.xml", handler);
handler.readList();
}
/*
* When the parser encounters plain text (not XML elements),
* it calls(this method, which accumulates them in a string buffer
*/
publicvoid characters(char[]
buffer, int start,int length) {
temp =new String(buffer, start, length);
}
/*
* Every time the parser encounters the beginning of a new element,
* it calls this method, which resets the string buffer
*/
publicvoid startElement(String uri, String localName,
String qName, Attributes attributes)throws SAXException {
temp ="";
if (qName.equalsIgnoreCase("Account")) {
acct =new Account();
acct.setType(attributes.getValue("type"));
}
}
/*
* When the parser encounters the end of an element, it calls this method
*/
publicvoid endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("Account")) {
// add it to
the list
accList.add(acct);
} elseif (qName.equalsIgnoreCase("Name"))
{
acct.setName(temp);
} elseif (qName.equalsIgnoreCase("Id"))
{
acct.setId(Integer.parseInt(temp));
} elseif (qName.equalsIgnoreCase("Amt"))
{
acct.setAmt(Integer.parseInt(temp));
}
}
privatevoid readList() {
System.out.println("No ofthe
accounts in bank '" +accList.size() +"'.");
Iterator<Account> it =
accList.iterator();
while (it.hasNext()) {
System.out.println(it.next().toString());
}
}
}
Output:
No of the accounts in bank '2'.
Account Details - Name:Jack Robinson, Type:saving, Id:1001, Age:10000.
Account Details - Name:Sony Corporation, Type:current, Id:1002, Age:1000000.
Advantage of SAX parser in Java:
It is faster than DOM parser because it will not load the XML document into the memory .its an event based.
Read more: http://javarevisited.blogspot.com/2011/12/parse-read-xml-file-java-sax-parser.html#ixzz2ki8zt0cQ
which we had discussed in last article of this series. Thistutorial is can be useful for those who are new to the java world and got the requirement forread
an xml file in java in their project or assignment, key feature of java is it provides built in class and object tohandle everything which makes our task
very easy. Basically this process of handling XML file is known asparsing means break down the whole string into small pieces using the special tokens.
Parsing can be done using two ways:
Using DOM Parser
Using SAX Parser
Read XML file in Java Using SAX Parser Example
In DOM parser we have seen that we have to follow simple three steps:Ø Parse the XML file
Ø Create the java object
Ø Manipulate the object means we can read that object or add them to list or whatever function we want we can do
But in SAX Parser its little bit different.
SAX
Parser: it’s an event based parsing it contains default handler for handling the events whenever SAX parser pareses the xml document and it finds theStart tag “<” and end tag”>”
it calls corresponding handler method.
Though there are other ways also to get data from xml file e.g. using
XPATH in Java which is a language like SQL and give selective data from xml file.
Sample Example of reading XML File – SAX Parser
Suppose we have this sample XML file bank.xml which containsaccountdetails of all accounts in a hypothetical bank:
<?xmlversion="1.0"encoding="UTF-8"?>
<Bank>
<Accounttype="saving">
<Id>1001</Id>
<Name>Jack Robinson</Name>
<Amt>10000</Amt>
</Account>
<Accounttype="current">
<Id>1002</Id>
<Name>Sony Corporation</Name>
<Amt>1000000</Amt>
</Account>
</Bank>
1. Create the SAX parser and parse the XML file: In this step we will take one factory instance fromSAXParserFactory
to parse the xml file this factory instance in turns give us instance of parser using theparse() method will parse the Xml file.
2. Event Handling: when Sax Parser starts the parsing whenever it founds thestart or end tag it will invoke the corresponding event handling
method which ispublic void startElement (…) and public void end Element (...).
3. Register the events: The class extends the Default Handler class tolisten for callback events and we register this handler to sax Parser
to notify us for call back event
Let see java code for all these steps
To represent data from our sample xml file we need one java domain object called Account:
package parser;
publicclass Account {
private Stringname;
privateintid;
privateintamt;
private Stringtype;
public Account() {
}
public Account(String name,int id,int
amt, String type) {
this.name = name;
this.amt = amt;
this.id = id;
this.type = type;
}
publicint getAmt() {
returnamt;
}
publicvoid setAmt(int amt)
{
this.amt = amt;
}
publicint getId() {
returnid;
}
publicvoidsetId(int
id) {
this.id = id;
}
public String getName() {
returnname;
}
publicvoid setName(String name) {
this.name = name;
}
public String getType() {
returntype;
}
publicvoid setType(String type) {
this.type = type;
}
public String toString() {
StringBuffer sb =
new StringBuffer();
sb.append("Account Details - ");
sb.append("Name:" + getName());
sb.append(", ");
sb.append("Type:" + getType());
sb.append(", ");
sb.append("Id:" + getId());
sb.append(", ");
sb.append("Age:" + getAmt());
sb.append(".");
return sb.toString();
}
}
Sample Code for implementing SAX parser in Java
package parser;import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
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;
publicclass ReadXMLFileUsingSaxparserextends
DefaultHandler {
private Accountacct;
private Stringtemp;
private ArrayList<Account>accList =
new ArrayList<Account>();
/** The
main method sets things up for parsing */
publicstaticvoid main(String[] args)throws
IOException, SAXException,
ParserConfigurationException {
//Create a "parser factory" for creating SAX parsers
SAXParserFactory spfac = SAXParserFactory.newInstance();
//Now use the parser factory to create a SAXParser object
SAXParser sp = spfac.newSAXParser();
//Create an instance of this class; it defines all the handler methods
ReadXMLFileUsingSaxparser handler =new ReadXMLFileUsingSaxparser();
//Finally, tell the parser to parse the input and notify the handler
sp.parse("bank.xml", handler);
handler.readList();
}
/*
* When the parser encounters plain text (not XML elements),
* it calls(this method, which accumulates them in a string buffer
*/
publicvoid characters(char[]
buffer, int start,int length) {
temp =new String(buffer, start, length);
}
/*
* Every time the parser encounters the beginning of a new element,
* it calls this method, which resets the string buffer
*/
publicvoid startElement(String uri, String localName,
String qName, Attributes attributes)throws SAXException {
temp ="";
if (qName.equalsIgnoreCase("Account")) {
acct =new Account();
acct.setType(attributes.getValue("type"));
}
}
/*
* When the parser encounters the end of an element, it calls this method
*/
publicvoid endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("Account")) {
// add it to
the list
accList.add(acct);
} elseif (qName.equalsIgnoreCase("Name"))
{
acct.setName(temp);
} elseif (qName.equalsIgnoreCase("Id"))
{
acct.setId(Integer.parseInt(temp));
} elseif (qName.equalsIgnoreCase("Amt"))
{
acct.setAmt(Integer.parseInt(temp));
}
}
privatevoid readList() {
System.out.println("No ofthe
accounts in bank '" +accList.size() +"'.");
Iterator<Account> it =
accList.iterator();
while (it.hasNext()) {
System.out.println(it.next().toString());
}
}
}
Output:
No of the accounts in bank '2'.
Account Details - Name:Jack Robinson, Type:saving, Id:1001, Age:10000.
Account Details - Name:Sony Corporation, Type:current, Id:1002, Age:1000000.
Advantage of SAX parser in Java:
It is faster than DOM parser because it will not load the XML document into the memory .its an event based.
Read more: http://javarevisited.blogspot.com/2011/12/parse-read-xml-file-java-sax-parser.html#ixzz2ki8zt0cQ
相关文章推荐
- How to Parse or Read XML File in Java >> XML Tutorial Example
- How To Read XML File In Java – (DOM Parser)
- Step-By-Step Guide to Get Started with Salesforce REST API using Java
- How to read file in Java – BufferedInputStream Example
- Step-by-step guide on File-to-IDoc using SAP PI 7.0
- Step-By-Step Guide To Create Physical Standby On Normal File System For ASM Primary using RMAN
- A simple way to read an XML file in Java
- Step-By-Step Guide To Create Physical Standby On Normal File System For ASM Primary using RMAN (文档 I
- JDOM Example : Reading and Parsing XML with SAX parser in Java
- Implementing Sugarcrm: A Step-by-step Guide to Using This Powerful Open Source Application in Your B
- How To Read XML File In Java – (SAX Parser)
- How To Create XML File In Java – (DOM Parser)
- A Step-by-Step Guide to Using iAd Workbench to Promote Your iOS Apps June 11, 2013, Raymond in Badmi
- How to Read, Write XLSX File in Java - Apach POI Example---reference
- Units Problem: How to read text size as custom attr from xml and set it to TextView in java code
- Step by Step Guide to Add a SQL Job in SQL Server 2005
- How to Read and Understand a Scientific Paper: A Step-by-Step Guide for Non-Scientists
- BI Java 补丁错误处理 :Cannot login to the SAP J2EE Engine using user and password as provided in the Filesystem Secure Store. Enter va
- Convert SVG to PDF by using iText in Java(ZT)
- Units Problem: How to read text size as custom attr from xml and set it to TextView in java code