Sunday, 4 January 2015

Java - SAX - Examples

Example 1


Create one java project in eclipse and add the following program in your project.

The xmlfile1.xml should be placed under project. To do this Right Click on project name and paste the xmlfile1.xml.

SAXParser1

package org.chidams.sax;


import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
class SAXParser1
{
public static void main(String args[])
{
try
{
//javax.xml.parsers
SAXParserFactory spf=SAXParserFactory.newInstance();
//javax.xml.parsers
SAXParser parser=spf.newSAXParser();
MyDefaultHandler1 mdh=new MyDefaultHandler1();
FileInputStream is=new FileInputStream("xmlfile1.xml");
parser.parse(is,mdh);
}//try
catch(Exception e)
{
e.printStackTrace();
}
}
}

class MyDefaultHandler1 extends org.xml.sax.helpers.DefaultHandler
{
StringBuffer buffer=new StringBuffer();
public void startElement(String uri,String localName,String qName,Attributes attributes)throws SAXException
{

System.out.println("startElement="+qName);
buffer.setLength(0);
}

public void characters(char ch[],int start,int end)
{

buffer.append(ch,start,end);
if (buffer.toString().length()!=0)
{
System.out.print("Value="+buffer.toString()+"\n");
}

}

public void endElement(String uri,String localName,String qName)throws org.xml.sax.SAXException
{

System.out.println("endElemnt="+qName);
buffer.setLength(0);
}
}

xmlfile1.xml

<?xml version="1.0"?>
<!--XMLTextWriter Example-->
<products>
<product>
<type>Keyboard</type>
<price>600.00</price>
<company>TVS</company>
</product>
<item>
<type>Monitor</type>
<price>6000.00</price>
<company>Samsung</company>
</item>

</products>

Output

startElement=products
Value=

startElement=product
Value=

startElement=type
Value=Keyboard
endElemnt=type
Value=

startElement=price
Value=600.00
endElemnt=price
Value=

startElement=company
Value=TVS
endElemnt=company
Value=

endElemnt=product
Value=

startElement=item
Value=

startElement=type
Value=Monitor
endElemnt=type
Value=

startElement=price
Value=6000.00
endElemnt=price
Value=

startElement=company
Value=Samsung
endElemnt=company
Value=

endElemnt=item
Value=


endElemnt=products


In output some values are empty and some values have the data. Can you understand why it is.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.