使用DOM方式,Java解析XML基本步驟:
首先,我們需要建立一個解析器工廠。
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
然后可以利用這個工廠來獲得一個具體的解析對象。
DocumentBuilder builder=dbf.newDocumentBuilder();
DocumentBuilder的Parse()方法接受一個XML文檔名作為輸入參數,返回一個Document對象。Document對象代表了 一個XML文檔的樹模型。
Document doc=builder.parse("candiate.xml");
使用Document對象的getElementsByTagName()方法,我們可以得到一個NodeList對象,他是XML文檔中的標簽元素 列表,可以使用NodeList對象的item()方法來得列表中的每一個Node對象。
NodeList nl=doc.getElementsByTagName("PERSON");
Element node=(Element)nl.item(i);
最后,我們會使用Node對象的getNodeValue()方法提取某個標簽內的內容。
node.getElementsByTagName("NAME").item(0).getFirstChild().getNodeValue()
完整程序代碼:
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class dom {
public static void main(String args[]){
String uri=args[0];
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//建立一個解析器工廠。
DocumentBuilder builder=factory.newDocumentBuilder();//獲得一個具體的解析對象。
Document doc=builder.parse(uri);//返回一個Document對象。
System.out.println(doc.getImplementation());
NodeList nl =doc.getElementsByTagName("PERSON");//得到一個NodeList對象。
for (int i=0;i<nl.getLength();i++){
Element node=(Element) nl.item(i);//得列表中的每一個Node對象。
System.out.print("NAME: ");
System.out.println (node.getElementsByTagName("NAME").item(0).getFirstChild().getNodeValue());
System.out.print("ADDRESS: ");
System.out.println (node.getElementsByTagName("ADDRESS").item(0).getFirstChild().getNodeValue());
System.out.print("TEL: ");
System.out.println (node.getElementsByTagName("TEL").item(0).getFirstChild().getNodeValue());
System.out.print("FAX: ");
System.out.println (node.getElementsByTagName("FAX").item(0).getFirstChild().getNodeValue());
System.out.print("EMAIL: ");
System.out.println (node.getElementsByTagName("EMAIL").item(0).getFirstChild().getNodeValue());
System.out.println();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
posted on 2006-07-02 10:21
磐石 閱讀(3433)
評論(0) 編輯 收藏