Simple API for XML
SAX是一套API,不是一个解析器,所以这个代码在XML解析器中是通用的。要让示例跑起来,需要一个支持SAX v2的XML解析器。实现了SAX的解析器有很多,比如Apache的Xerces,Oracle的XML Parser等等。
解析时需实现ContentHandler或者扩展DefaultHandler类,将XML解析器解析一个特定的文档即可。示例:
xml文件
<?xml version="1.0"?>
<simple date="7/7/2000" >
<name> Bob </name>
<location> New York </location>
</simple>
接下来,我们看看第一个XML解析例子的代码:
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;
public class Example1 extends DefaultHandler {
// 重载DefaultHandler类的方法
// 以拦截SAX事件通知。
//
// 关于所有有效事件,见org.xml.sax.ContentHandler
//
public void startDocument( ) throws SAXException {
System.out.println( "SAX Event: START DOCUMENT" );
}
public void endDocument( ) throws SAXException {
System.out.println( "SAX Event: END DOCUMENT" );
}
public void startElement( String namespaceURI,
String localName,
String qName,
Attributes attr ) throws SAXException {
System.out.println( "SAX Event: START ELEMENT[ " +
localName + " ]" );
// 如果有属性,我们也一并打印出来...
for ( int i = 0; i < attr.getLength(); i++ ){
System.out.println( " ATTRIBUTE: " +
attr.getLocalName(i) +
" VALUE: " +
attr.getValue(i) );
}
}
public void endElement( String namespaceURI,
String localName,
String qName ) throws SAXException {
System.out.println( "SAX Event: END ELEMENT[ " +
localName + " ]" );
}
public void characters( char[] ch, int start, int length )
throws SAXException {
System.out.print( "SAX Event: CHARACTERS[ " ];
try {
OutputStreamWriter outw = new OutputStreamWriter(System.out);
outw.write( ch, start,length );
outw.flush();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println( " )" );
}
public static void main( String[] argv ){
System.out.println( "Example1 SAX Events:" );
try {
// 建立SAX 2解析器...
XMLReader xr = XMLReaderFactory.createXMLReader();
// 安装ContentHandler...
xr.setContentHandler( new Example1() );
// 解析文件...
xr.parse( new InputSource(
new FileReader( "Example1.xml" )) );
}catch ( Exception e ) {
e.printStackTrace();
}
}
}
最后,就得到了运行第一个例子解析我们的XML样本文档所产生的输出:
Example1 SAX Events:
SAX Event: START DOCUMENT
SAX Event: START ELEMENT[ simple ]
ATTRIBUTE: date VALUE: 7/7/2000
SAX Event: CHARACTERS[
]
SAX Event: START ELEMENT[ name ]
SAX Event: CHARACTERS[ Bob ]
SAX Event: END ELEMENT[ name ]
SAX Event: CHARACTERS[
]
SAX Event: START ELEMENT[ location ]
SAX Event: CHARACTERS[ New York ]
SAX Event: END ELEMENT[ location ]
SAX Event: CHARACTERS[
]
SAX Event: END ELEMENT[ simple ]
SAX Event: END DOCUMENT
如你所见,SAX解析器会为每个在XML文档中出现的SAX事件调用正确的ContentHandler成员方法。
posted on 2007-05-31 16:20
李大嘴 阅读(420)
评论(0) 编辑 收藏