1.使用dom4j解析XML檔案,dom4j解析xml檔案

來源:互聯網
上載者:User

1.使用dom4j解析XML檔案,dom4j解析xml檔案

一.dom4j的簡介

 

dom4j是一個Java的XML API,是jdom的升級品,用來讀寫XML檔案的。dom4j是一個十分優秀的JavaXML API,具有效能優異、功能強大和極其易使用的特點,它的效能超過sun公司官方的dom技術,同時它也是一個開放原始碼的軟體,可以在SourceForge上找到它。在IBM developerWorks上面還可以找到一篇文章,對主流的Java XML API進行的效能、功能和易用性的評測,所以可以知道dom4j無論在哪個方面都是非常出色的。如今可以看到越來越多的Java軟體都在使用dom4j來讀寫XML,特別值得一提的是連Sun的JAXM也在用dom4j。這已經是必須使用的jar包, Hibernate也用它來讀寫設定檔。

二.dom4j的簡單解析1.匯入dom4j的Maven依賴
<!-- parser xml file --><dependency>  <groupId>org.dom4j</groupId>  <artifactId>dom4j</artifactId>  <version>2.1.0</version></dependency>

 

2.建立userConfig.xml檔案

 

<?xml version="1.0" encoding="UTF-8"?><users>    <user>        <userName>user1</userName>        <password>123</password>        <systemId>AAA</systemId>    </user>    <user>        <userName>user2</userName>        <password>456</password>        <systemId>BBB</systemId>    </user></users>

 

3.使用SAXReader類 和解析 xml檔案
package com.my.utils;import java.io.File;import java.util.List;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;public class ReadXMLConfig {    public static void main(String[] args) {        // TODO Auto-generated method stub                //define config file path         //String path = this.getClass().getClassLoader().getResource("").getPath()+"config/userConfig.xml";        String path = "src/main/resources/config/userConfig.xml";                SAXReader reader = new SAXReader();        reader.setEncoding("utf-8");        Document document = null;        try {            document = reader.read(new File(path));                        Element root = document.getRootElement();                        //get user list             List<Element> list = root.elements("user");            Element use1 = list.get(0);                        //get user info            System.out.println(use1.element("userName").getStringValue());            System.out.println(use1.element("password").getStringValue());            System.out.println(use1.element("systemId").getStringValue());        } catch (DocumentException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

輸入結果如下:

user1123AAA

對於解析每個user info 的部分,這裡只是做了簡單的解析

如有問題歡迎留言,看到後會第一時間為你解決.

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.