XMLReader vs SAXParser
843834Feb 5 2006 — edited Feb 6 2006Hi all,
I have a couple of doubts plz help me out of them:-
1. Can you tell me what is the advantage of using parse() of XMLReader over parse() of SAXParser.
2. In the following code I can read and print the qName in the endElements() but i can't print the qName using the startElement(). Plz tell me where i have gone wrong. I'll be really greateful to you.
Thanks.
My Code:-
import javax.xml.parsers.*;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import java.util.jar.Attributes;
import java.io.File;
class Reading extends DefaultHandler
{
public static void main(String args[])throws Exception
{
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
File file=new File("first.xml");
sp.parse(file,new Reading());
/*XMLReader xmlr=sp.getXMLReader();
xmlr.setContentHandler(new Reading());
xmlr.parse("first.xml");*/
}
public void startElement(String uri,String localName,String qName, Attributes attributes)
{
System.out.println(qName);
}
public void characters(char []ch,int start,int length)
{
String str=new String(ch,start,length);
System.out.print(str);
}
public void endElement(String uri,String localName,String qName)
{
System.out.println(qName);
}
}
This is my XML file:-
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Avneet Gambhir</to>
<from>Yahoo</from>
<message>Hi how "are" you</message>
<to>Deepu</to>
<from>Avneet</from>
<message>Hi</message>
</note>
This is my output:-
c:\avneet\XML examples>java Reading
Avneet Gambhirto
Yahoofrom
Hi how "are" youmessage
Deeputo
Avneetfrom
Himessage
note