代碼:

import org.xml.sax.Attributes;

import org.xml.sax.SAXException;

import org.xml.sax.Locator;

import org.xml.sax.ContentHandler;

import org.xml.sax.InputSource;

import org.xml.sax.helpers.DefaultHandler;

import java.io.IOException;

import javax.xml.parsers.SAXParser;

import javax.xml.parsers.SAXParserFactory;


class TestSAX extends DefaultHandler{
private StringBuffer buf;
private String str;
public TestSAX(){
super();
}
// public void setDocumentLocator(Locator locator){}
public void startDocument() throws SAXException{
buf=new StringBuffer();
System.out.println("*******開始解析文檔*******");
public void endDocument() throws SAXException{
System.out.println("*******文檔解析結束*******");
public void startPrefixMapping( String prefix, String uri ){
System.out.println(" 字首映射: " + prefix +" 開始!"+ " 它的URI是:" + uri);
public void endPrefixMapping( String prefix ){
System.out.println(" 字首映射: "+prefix+" 結束!");
// public void processingInstruction( String target, String instruction )throws SAXException{}
// public void ignorableWhitespace( char[] chars, int start, int length ) throws SAXException {}
// public void skippedEntity( String name ) throws SAXException {}
public void startElement(String namespaceURI,String localName,String qName,Attributes atts){
System.out.println("*******開始解析元素*******");
System.out.println("元素名"+qName);
for(int i=0;i<atts.getLength();i++){
System.out.println("元素名"+atts.getLocalName(i)+"屬性值"+atts.getValue(i));
}
public void endElement(String namespaceURI,String localName,String fullName )throws SAXException{
// buf.trimToSize();
str = buf.toString();
System.out.println("buf = "+buf+" || length = "+buf.length());
System.out.println("str = "+str.trim()+" || length = "+str.trim().length());
buf.delete(0,buf.length());
System.out.println("******"+namespaceURI+"元素解析結束"+localName+"********"+fullName);
public void characters( char[] chars, int start, int length )throws SAXException{
//将元素内容累加到StringBuffer中
buf.append(chars,start,length);
public static void main(String args[]){
try{
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sp = sf.newSAXParser();
TestSAX testsax=new TestSAX();
sp.parse(new InputSource("test1.xml"),testsax);
}catch(IOException e){
e.printStackTrace();
}catch(SAXException e){
}catch(Exception e){
}
xml檔案,我讀的時候有錯誤,用了自己的,希望其他人比我幸運!

<?xml version="1.0" encoding="GB2312"?>

<row>

<person>

<name>王小明</name>

<college>資訊學院</college>

<telephone>6258113</telephone>

<notes>男,1955年生,博士,95年調入海南大學</notes>

</person>

</row>