明辉站/网站教程/内容

Java+XML学习Step by step(一)

网站教程2024-02-18 阅读
[摘要]Belltree 发表于 2001-10-25 09:08 XML学习 ←返回版面 啊,各位兄弟,找了几个jaxp和xerces的例子,做了一些注释,希望对大家的学习有帮助,下面这个例子是jaxp包中带的例子:CountDom.java,这个例子要点有:如何得到一个Document对象,以及对节点...
 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;
}
}


……

相关阅读