belltree 发表于 2001-10-25 09:08 xml学习 ←返回版面
啊,各位兄弟,找了几个jaxp和xerces的例子,做了一些注释,希望对大家的学习有帮助,下面这个例子是jaxp包中带的例子:countdom.java,这个例子要点有:如何得到一个document对象,以及对节点类型的判断。可以看到,jaxp程序都从得到一个documentbuilderfactory实例开始,再从中获得documentbuilder实例,documentbuilder实例就可以新建一个空的document或者parse一个已有的xml文档。
/*
* 使用dom方法来遍历xml树中的所有节点,对节点类型为element的进行统计
*/
import java.io.*;
// import jaxp包
import org.w3c.dom.*; // 这个里面主要定义了一系列的interface
import org.xml.sax.*; // 为什么要载入这个包呢,我认为是因为要抛出异常,解析xml的异常在sax中
// 都定义好了,所以dom就直接用了
import javax.xml.parsers.documentbuilderfactory; // factory api,用来获得一个parser
import javax.xml.parsers.documentbuilder; // 用来从xml文档中获得dom文档实例
public class countdom {
/* main函数,这个就不用讲了,调用getelementcount(),arg参数就是要处理的xml文件名 */
public static void main(string[] args) throws exception {
for (int i = 0; i < args.length; i++) {
string arg = args[i];
system.out.println(arg + " elementcount: " + getelementcount(arg));
}
}
/* 调用 getelementcount(node),node是节点 */
public static int getelementcount(string filename) throws exception {
node node = readfile(filename); // readfile(string)获得一个文件实例
// readfile(file)返回document
return getelementcount(node); // 统计elements
}
/* 创建文件对象, 调用 readfile(file) */
public static document readfile(string filename) throws exception {
if (null == filename) {
throw new exception("no filename for readfile()");
}
return readfile(new file(filename));
}
/* 解析文档,返回 document */
public static document readfile(file file) throws exception {
document doc;
try {
/* 首先获得一个 documentbuilderfactory 的实例 */
documentbuilderfactory dbf = documentbuilderfactory.newinstance();
/* 下面看是不是要对xml文档进行有效性判断,缺省是false */
// dbf.setvalidating(true);
/* 创建一个 documentbuilder 的实例*/
documentbuilder db = dbf.newdocumentbuilder();
/* 解析文档 */
doc = db.parse(file);
/* 返回一个 document 实例*/
return doc;
} catch (saxparseexception ex) {
throw (ex);
} catch (saxexception ex) {
exception x = ex.getexception(); // get underlying exception
throw ((x == null) ? ex : x);
}
}
/*
* 使用dom方法来统计 elements
*/
public static int getelementcount(node node) {
/* 如果node为空的话,然回0 */
if (null == node) {
return 0;
}
int sum = 0;
// 首先,第一个是节点的根,判断一下是不是element
boolean iselement = (node.getnodetype() == node.element_node);
// 如果节点的根是element节点,那sum的初始值就是1
if (iselement) {
sum = 1;
}
// 发挥节点的所有子节点
nodelist children = node.getchildnodes();
// 没有任何子节点的情况下,返回当前值
if (null == children) {
return sum;
}
// 遍历节点的所有子节点
for (int i = 0; i < children.getlength(); i++) {
//用递归
sum += getelementcount(children.item(i));
}
return sum;
}
}
