一.java類
- package com.java.test;
- import org.w3c.dom.*;
- import javax.xml.parsers.*;
- import java.io.*;
- public class JavaReadXml {
- // Document可以看作是XML在記憶體中的一個鏡像,那麼一旦擷取這個Document 就意味著可以通過對
- // 記憶體的操作來實現對XML的操作,首先第一步擷取XML相關的Document
- private Document doc = null;
- public void init(String xmlFile) throws Exception {
- // 很明顯該類是一個單例,先擷取產生DocumentBuilder工廠
- // 的工廠,在通過這個工廠產生一個DocumentBuilder,
- // DocumentBuilder就是用來產生Document的
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- DocumentBuilder db = dbf.newDocumentBuilder();
- // 這個Document就是一個XML檔案在記憶體中的鏡像
- doc = db.parse(new File(xmlFile));
- }
- // 該方法負責把XML檔案的內容顯示出來
- public void viewXML(String xmlFile) throws Exception {
- this.init(xmlFile);
- // 在xml檔案裡,只有一個根項目,先把根項目拿出來看看
- Element element = doc.getDocumentElement();
- System.out.println("根項目為:" + element.getTagName());
- NodeList nodeList = doc.getElementsByTagName("person");
- System.out.println("book節點鏈的長度:" + nodeList.getLength());
- Node fatherNode = nodeList.item(0);
- System.out.println("父節點為:" + fatherNode.getNodeName());
- // 把父節點的屬性拿出來
- NamedNodeMap attributes = fatherNode.getAttributes();
- for (int i = 0; i < attributes.getLength(); i++) {
- Node attribute = attributes.item(i);
- System.out.println("book的屬性名稱為:" + attribute.getNodeName()
- + " 相對應的屬性值為:" + attribute.getNodeValue());
- }
- NodeList childNodes = fatherNode.getChildNodes();
- System.out.println(childNodes.getLength());
- for (int j = 0; j < childNodes.getLength(); j++) {
- Node childNode = childNodes.item(j);
- // 如果這個節點屬於Element ,再進行取值
- if (childNode instanceof Element) {
- // System.out.println("子節點名為:"+childNode.getNodeName()+"相對應的值為"+childNode.getFirstChild().getNodeValue());
- System.out.println("子節點名為:" + childNode.getNodeName()
- + "相對應的值為" + childNode.getFirstChild().getNodeValue());
- }
- }
- }
- public static void main(String[] args) throws Exception {
- JavaReadXml parse = new JavaReadXml();
- // 我的XML檔案
- parse.viewXML("person.xml");
- }
- }
二.xml檔案
- <?xml version="1.0" encoding="UTF-8"?>
- <book>
- <person>
- <first>wang</first>
- <last>laohu</last>
- <age>25</age>
- <version>中國郵電出版社</version>
- </person>
- <person>
- <first>li</first>
- <last>junjia</last>
- <age>24</age>
- <version>清華大學出版社</version>
- </person>
- </book>
三.輸出結果
根項目為:book
book節點鏈的長度:2
父節點為:person
9
子節點名為:first相對應的值為wang
子節點名為:last相對應的值為laohu
子節點名為:age相對應的值為25
子節點名為:version相對應的值為中國郵電出版社