SAX对底层操作的事例
SAX是基于事件的API,运行比DOM更为底层的操作,相对DOM而言有更多的控制权,几乎总是比DOM效率高,不过它需要做更多的工作。。
下面的这个例子将打印出product.xml文档中所有的questions:

package sax.wkjava;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXDemo {

public SAXDemo() throws FileNotFoundException,
ParserConfigurationException, SAXException, IOException {
printQuestions("product.xml");
}

public static void main(String[] args) {
try {
new SAXDemo();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public void printQuestions(String xmlfile)
throws ParserConfigurationException, SAXException,
FileNotFoundException, IOException {

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();

parser.parse(new FileInputStream(xmlfile), new DefaultHandler() {

private boolean isQuestions = false;

public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
if (qName.equals(
"questions")) {
isQuestions = true;
}
}

public void characters(char[] ch, int start, int length)
throws SAXException {
if (isQuestions) {
String str = new String(ch, start, length);

System.out.println(str);

}
}

public void endElement(String uri, String localName,
String qName) throws SAXException {
if (qName.equals(
"questions")) {
isQuestions = false;
}
}

});

}
}

//product.xml中code如下:
<?xml version=
"1.0" encoding="UTF-8"?>
<!-- product.xml -->
<product id=
"200">
<name>UML Exam Simulator</name>
<price>100</price>
<topics name=
"UML">
<topic id=
"UML_SM">
<name>Static Modeling</name>
<questions>100</questions>
</topic>
<topic id=
"UML_AE">
<name>Architecture</name>
<questions>80</questions>
</topic>
<topic id=
"UML_DM">
<name>Dynamic Modeling</name>
<questions>67</questions>
</topic>
</topics>
</product>
weiking   2006-04-20 16:18:58 评论:0   阅读:277   引用:0

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

用,就用的漂亮点。文章嘛,借花献佛喽。