2014年12月31日08:36:29 天氣晴
首先我們學習一下基本的知識
一DOM樹節點概念
根據DOM,XML文檔中的每個成分都是一個節點
DOM是這樣規定的:
1、整個文檔是一個文檔節點(Document Node)
2、每個XML的標籤是一個元素節點(Element Node)
3、包含在XML元素中的文本是文本節點(Text Node)
4、每一個XML屬性是一個屬性節點(Attirbute Node)
5、註釋屬於註釋節點(Annotation Node)
二DOM解析編程過程步驟:dom4j下載地址
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student id="studentId">
<name>LGP</name>
<age>24</age>
</student>
</students>
package com.gditc.test;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ReadXmlByDOM {
public static void main(String[] args) {
readXmlFileByDom("xml/student.xml");
}
private static void readXmlFileByDom(String xmlFile) {
try {
//創建一個解析器工廠
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//創建一個解析器對象
DocumentBuilder db = dbf.newDocumentBuilder();
//創建一個文檔對象,到此,在內存裏就會形成與該XML文檔對象的一個"樹模型"
Document document = db.parse(new File(xmlFile));
System.out.println("【獲得文檔樹基本信息如下】:");
System.out.println("xml版本"+document.getXmlVersion());
System.out.println("xml編碼"+document.getXmlEncoding());
System.out.println("是否實體引用"+document.getXmlStandalone());
System.out.println("【獲得學生信息如下】:");
NodeList nodeList = document.getElementsByTagName("student");
//理解後寫的,這是已知道xml的結構下做的遍歷
for (int i=0; i<nodeList.getLength(); i++) {
Node node = nodeList.item(i);
NodeList nodeList2 = node.getChildNodes();
System.out.println(nodeList2.getLength());
for (int j=0; j<nodeList2.getLength(); j++) {
Node node2 = nodeList2.item(j);
if (node2 instanceof Element) {
Element e = (Element) node2;
System.out.println(e.getNodeName()+":"+e.getTextContent());
}
}
}
/*//參考
for (int i=0; i<nodeList.getLength(); i++) {
//studentNode是student節點
Node studentNode = nodeList.item(i);
if (studentNode instanceof Element) {
Element studentElement = (Element) studentNode;
String attrId = studentElement.getAttribute("id");
System.out.println("id屬性值"+attrId);
//subNodeList代表Student節點下的所有子節點列表
NodeList subNodeList = studentElement.getChildNodes();
System.out.println("【學生信息如下】:");
for (int j=0; j<subNodeList.getLength(); j++) {
Node subStudentNode = subNodeList.item(j);
//由於xml文檔可以存在空文本節點,因此,需要對此情況做處理
if (subStudentNode instanceof Element) {
Element e = (Element) subStudentNode;
System.out.println(e.getTagName()+":"+e.getTextContent());
}
}
}
}*/
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}