Sax.java
/*
* Copyright@ 2011 www.egtry.com
*/
package egtry.xml;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
public class Sax {
public static void main(String[] args) throws Exception {
//step 1. get SAXParser
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser saxParser=factory.newSAXParser();
//step 2. parse a xml source with its handler
String xml="<root><a n=\"1\"></a></root>";
InputStream in=new StringBufferInputStream(xml);
saxParser.parse(in, new SaxHandler1());
System.out.println("Done");
}
public static class SaxHandler1 extends DefaultHandler{
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
System.out.println("StartElement uri="+uri+", localName="+localName+", qName="+qName);
if (attributes.getLength()>0) {
for(int i=0; i<attributes.getLength(); i++) {
System.out.print(" "+attributes.getQName(i)+"=\""+attributes.getValue(i)+"\"");
}
System.out.println("\n");
}
}
}
}
Output
StartElement uri=, localName=, qName=root
StartElement uri=, localName=, qName=a
n="1"
Done