Belltree 發(fā)表于 2001-10-25 09:08 XML學(xué)習(xí) ←返回版面
啊,各位兄弟,找了幾個jaxp和xerces的例子,做了一些注釋,希望對大家的學(xué)習(xí)有幫助,下面這個例子是jaxp包中帶的例子:CountDom.java,這個例子要點(diǎn)有:如何得到一個Document對象,以及對節(jié)點(diǎn)類型的判斷。可以看到,jaxp程序都從得到一個DocumentBuilderFactory實例開始,再從中獲得DocumentBuilder實例,DocumentBuilder實例就可以新建一個空的Document或者parse一個已有的xml文檔。
/* * 使用DOM方法來遍歷XML樹中的所有節(jié)點(diǎn),對節(jié)點(diǎn)類型為ELEMENT的進(jìn)行統(tǒng)計 */ import java.io.*;
// import JAXP包 import org.w3c.dom.*; // 這個里面主要定義了一系列的Interface
import org.xml.sax.*; // 為什么要載入這個包呢,我認(rèn)為是因為要拋出異常,解析XML的異常在SAX中 // 都定義好了,所以DOM就直接用了
import javax.xml.parsers.DocumentBuilderFactory;// factory API,用來獲得一個parser import javax.xml.parsers.DocumentBuilder; // 用來從XML文檔中獲得DOM文檔實例
public class CountDom {
/* main函數(shù),這個就不用講了,調(diào)用getElementCount(),arg參數(shù)就是要處理的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)); } }
/* 調(diào)用 getElementCount(Node),Node是節(jié)點(diǎn) */ public static int getElementCount(String fileName) throws Exception { Node node = readFile(fileName); // readFile(String)獲得一個文件實例 // readFile(File)返回Document return getElementCount(node); // 統(tǒng)計Elements }
/* 創(chuàng)建文件對象, 調(diào)用 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文檔進(jìn)行有效性判斷,缺省是false */ // dbf.setValidating(true);
/* 創(chuàng)建一個 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方法來統(tǒng)計 ELEMENTS */ public static int getElementCount(Node node) { /* 如果node為空的話,然回0 */ if (null == node) { return 0; } int sum = 0; // 首先,第一個是節(jié)點(diǎn)的根,判斷一下是不是ELEMENT boolean isElement = (node.getNodeType() == Node.ELEMENT_NODE); // 如果節(jié)點(diǎn)的根是ELEMENT節(jié)點(diǎn),那sum的初始值就是1 if (isElement) { sum = 1; } // 發(fā)揮節(jié)點(diǎn)的所有子節(jié)點(diǎn) NodeList children = node.getChildNodes();
// 沒有任何子節(jié)點(diǎn)的情況下,返回當(dāng)前值 if (null == children) { return sum; } // 遍歷節(jié)點(diǎn)的所有子節(jié)點(diǎn) for (int i = 0; i < children.getLength(); i++) { //用遞歸 sum += getElementCount(children.item(i)); } return sum; } }
|