XML的案例--1

http://blog.csdn.net/cuiweibing/article/details/1743235

http://www.cnblogs.com/macula/archive/2011/07/27/2118003.html

 

 

 

  下面的文章轉載至:http://lavasoft.blog.51cto.com/62575/66953

 
Dom4j解析需要XML需要的最小類庫爲:
dom4j-1.6.1.jar
jaxen-1.1-beta-6.jar
 
目標:
解析一個xml,輸出所有的屬性和元素值。
 
測試代碼:
 
XML文件:
<?xml version="1.0" encoding="GBK"?>
<doc>
    <person id="1" sex="m">
        <name>zhangsan</name>
        <age>32</age>
        <adds>
            <add code="home">home add</add>
            <add code="com">com add</add>
        </adds>
    </person>
    <person id="2" sex="w">
        <name>lisi</name>
        <age>22</age>
        <adds>
            <add ID="22" id="23" code="home">home add</add>
            <add ID="23" id="22" code="com">com add</add>
            <add id="24" code="com">com add</add>
        </adds>
    </person>
</doc>
 
 
解析代碼:
package com.topsoft.test;

import org.dom4j.io.SAXReader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;

import java.util.Iterator;
import java.util.List;
import java.io.InputStream;

/**
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-3-26 15:53:51<br>
* <b>Note</b>: Dom4j遍歷解析XML測試
*/

public class TestDom4j {
    /**
     * 獲取指定xml文檔的Document對象,xml文件必須在classpath中可以找到
     *
     * @param xmlFilePath xml文件路徑
     * @return Document對象
     */

    public static Document parse2Document(String xmlFilePath) {
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            InputStream in = TestDom4j.class.getResourceAsStream(xmlFilePath);
            document = reader.read(in);
        } catch (DocumentException e) {
            System.out.println(e.getMessage());
            System.out.println("讀取classpath下xmlFileName文件發生異常,請檢查CLASSPATH和文件名是否存在!");
            e.printStackTrace();
        }
        return document;
    }

    public static void testParseXMLData(String xmlFileName) {
        //產生一個解析器對象
        SAXReader reader = new SAXReader();
        //將xml文檔轉換爲Document的對象
        Document document = parse2Document(xmlFileName);
        //獲取文檔的根元素
        Element root = document.getRootElement();
        //定義個保存輸出xml數據的緩衝字符串對象
        StringBuffer sb = new StringBuffer();
        sb.append("通過Dom4j解析XML,並輸出數據:\n");
        sb.append(xmlFileName + "\n");
        sb.append("----------------遍歷start----------------\n");
        //遍歷當前元素(在此是根元素)的子元素
        for (Iterator i_pe = root.elementIterator(); i_pe.hasNext();) {
            Element e_pe = (Element) i_pe.next();
            //獲取當前元素的名字
            String person = e_pe.getName();
            //獲取當前元素的id和sex屬性的值並分別賦給id,sex變量
            String id = e_pe.attributeValue("id");
            String sex = e_pe.attributeValue("sex");
            String name = e_pe.element("name").getText();
            String age = e_pe.element("age").getText();
            //將數據存放到緩衝區字符串對象中
            sb.append(person + ":\n");
            sb.append("\tid=" + id + " sex=" + sex + "\n");
            sb.append("\t" + "name=" + name + " age=" + age + "\n");

            //獲取當前元素e_pe(在此是person元素)下的子元素adds
            Element e_adds = e_pe.element("adds");
            sb.append("\t" + e_adds.getName() + "\n");

            //遍歷當前元素e_adds(在此是adds元素)的子元素
            for (Iterator i_adds = e_adds.elementIterator(); i_adds.hasNext();) {
                Element e_add = (Element) i_adds.next();
                String code = e_add.attributeValue("code");
                String add = e_add.getTextTrim();
                sb.append("\t\t" + e_add.getName() + ":" + " code=" + code + " value=\"" + add + "\"\n");
            }
            sb.append("\n");
        }
        sb.append("-----------------遍歷end-----------------\n");
        System.out.println(sb.toString());


        System.out.println("---------通過XPath獲取一個元素----------");
        Node node1 = document.selectSingleNode("/doc/person");
        System.out.println("輸出節點:" +
                "\t"+node1.asXML());

        Node node2 = document.selectSingleNode("/doc/person/@sex");
        System.out.println("輸出節點:" +
                "\t"+node2.asXML());

        Node node3 = document.selectSingleNode("/doc/person[name=\"zhangsan\"]/age");
        System.out.println("輸出節點:" +
                "\t"+node3.asXML());

        System.out.println("\n---------XPath獲取List節點測試------------");
        List list = document.selectNodes("/doc/person[name=\"zhangsan\"]/adds/add");
        for(Iterator it=list.iterator();it.hasNext();){
            Node nodex=(Node)it.next();
            System.out.println(nodex.asXML());
        }

        System.out.println("\n---------通過ID獲取元素的測試----------");
        System.out.println("陷阱:通過ID獲取,元素ID屬性名必須爲“大寫ID”,小寫的“id”會認爲是普通屬性!");
        String id22 = document.elementByID("22").asXML();
        String id23 = document.elementByID("23").asXML();
        String id24 = null;
        if (document.elementByID("24") != null) {
            id24 = document.elementByID("24").asXML();
        } else {
            id24 = "null";
        }

        System.out.println("id22=  " + id22);
        System.out.println("id23=  " + id23);
        System.out.println("id24=  " + id24);
    }


    public static void main(String args[]) {
        testParseXMLData("/person.xml");
    }
}
 
 
運行結果:
通過Dom4j解析XML,並輸出數據:
/person.xml
----------------遍歷start----------------
person:
    id=1 sex=m
    name=zhangsan age=32
    adds
  add: code=home value="home add"
  add: code=com value="com add"

person:
    id=2 sex=w
    name=lisi age=22
    adds
  add: code=home value="home add"
  add: code=com value="com add"
  add: code=com value="com add"

-----------------遍歷end-----------------

---------通過XPath獲取一個元素----------
輸出節點:    <person id="1" sex="m">
        <name>zhangsan</name>
        <age>32</age>
        <adds>
            <add code="home">home add</add>
            <add code="com">com add</add>
        </adds>
    </person>
輸出節點:    sex="m"
輸出節點:    <age>32</age>

---------XPath獲取List節點測試------------
<add code="home">home add</add>
<add code="com">com add</add>

---------通過ID獲取元素的測試----------
陷阱:通過ID獲取,元素ID屬性名必須爲“大寫ID”,小寫的“id”會認爲是普通屬性!
id22=  <add ID="22" id="23" code="home">home add</add>
id23=  <add ID="23" id="22" code="com">com add</add>
id24=  null

Process finished with exit code 0
 
發個Idea7開發界面截圖: 點擊圖片放大
 
 
想從頭瞭解dom4j的朋友可以看dom4j文檔中的quick start,這個是E文版的,另外有熱心的網友已經將自己翻譯的中文版奉獻出來了,可以看看:

 

 

 

 

 

 

 

 

 

 

 

發佈了5 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章