下列代码说明这种ContentHandler轮换技术。Contents缓存被类Example6和其它特定ContentHandler内部类共享:
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;
import java.util.*;
import common.*;
public class Example6 extends DefaultHandler {
// XML解析...
XMLReader parser;
// 被解析对象...
Example6Circle circleMapper = new Example6Circle();
Example6Square squareMapper = new Example6Square();
Example6Triangle triangleMapper = new Example6Triangle();
// 不同形体的本地向量表...
private Vector circles = new Vector();
private Vector triangles = new Vector();
private Vector squares = new Vector();
// 从"characters" SAX事件中收集数据的缓存。
private CharArrayWriter contents = new CharArrayWriter();
// 用XML解析器为参数的构造函数...
Example6( XMLReader parser ) {
this.parser = parser;
}
// 重载DefaultHandler类以拦截SAX事件的方法。
//
// 头于所有有效事件的详细内容,参见org.xml.sax.ContentHandler。
//
public void startElement( String namespaceURI,
String localName,
String qName,
Attributes attr ) throws SAXException {
contents.reset();
if ( localName.equals( "Circle" ) ) {
Circle aCircle = new Circle();
aCircle.name = attr.getValue( "name" );
circles.addElement( aCircle );
circleMapper.collectCircle( parser, this, aCircle );
}
if ( localName.equals( "Square" ) ) {
Square aSquare = new Square();
aSquare.name = attr.getValue( "name" );
squares.addElement( aSquare );
squareMapper.collectSquare( parser, this, aSquare );
}
if ( localName.equals( "Triangle" ) ) {
Triangle aTriangle = new Triangle();
aTriangle.name = attr.getValue( "name" );
triangles.addElement( aTriangle );
triangleMapper.collectTriangle( parser, this, aTriangle);
}
}
public void endElement( String namespaceURI,
String localName,
String qName ) throws SAXException {
// endElement SAX事件中已经没有需要Example 6映射器处理的了。
}
public void characters( char[] ch, int start, int length )
throws SAXException {
// // 将数据内容写入缓存。
contents.write( ch, start, length );
}
public Vector getCircles() {
return circles;
}
public Vector getSquares() {
return squares;
}
public Vector getTriangles() {
return triangles;
}
public static void main( String[] argv ){
System.out.println( "Example6:" );
try {
// 创建SAX 2解析器...
XMLReader xr = XMLReaderFactory.createXMLReader();
// 安装ContentHandler...
Example6 ex6 = new Example6(xr);
xr.setContentHandler( ex6 );
// 解析文件...
xr.parse( new InputSource(
new FileReader( "Example6.xml" )) );
//将圆形对象显示到标准输出...
Circle c;
Vector items = ex6.getCircles();
Enumeration e = items.elements();
while( e.hasMoreElements()){
c = (Circle) e.nextElement();
c.print( System.out );
}
// // 将长方形对象显示到标准输出...
Square s;
items = ex6.getSquares();
e = items.elements();
while( e.hasMoreElements()){
s = (Square) e.nextElement();
s.print( System.out );
}
// 将三角形对象显示到标准输出...
Triangle t;
items = ex6.getTriangles();
e = items.elements();
while( e.hasMoreElements()){
t = (Triangle) e.nextElement();
t.print( System.out );
}
}catch ( Exception e ) {
e.printStackTrace();
}
}
}
(未完待续)
本文地址:http://com.8s8s.com/it/it18146.htm