dom4j解析xml字符串實例


DOM4J

 

    與利用DOM、SAX、JAXP機制來解析xml相比,DOM4J 表現更優秀,具有性能優異、功能強大和極端易用使用的特點,只要懂得DOM基本概念,就可以通過dom4j的api文檔來解析xml。dom4j是一套開源的api。實際項目中,往往選擇dom4j來作為解析xml的利器。

 

先來看看dom4j中對應XML的DOM樹建立的繼承關系

  

針對於XML標准定義,對應於圖2-1列出的內容,dom4j提供了以下實現:

  

同時,dom4j的NodeType枚舉實現了XML規范中定義的node類型。如此可以在遍歷xml文檔的時候通過常量來判斷節點類型了。

 

常用API

 

class org.dom4j.io.SAXReader

 

  • read  提供多種讀取xml文件的方式,返回一個Domcument對象

 

interface org.dom4j.Document

 

  • iterator  使用此法獲取node
  • getRootElement  獲取根節點

 

interface org.dom4j.Node

 

  • getName  獲取node名字,例如獲取根節點名稱為bookstore
  • getNodeType  獲取node類型常量值,例如獲取到bookstore類型為1——Element
  • getNodeTypeName  獲取node類型名稱,例如獲取到的bookstore類型名稱為Element

 

interface org.dom4j.Element

 

  • attributes  返回該元素的屬性列表
  • attributeValue  根據傳入的屬性名獲取屬性值
  • elementIterator  返回包含子元素的迭代器
  • elements  返回包含子元素的列表

 

interface org.dom4j.Attribute

 

  • getName  獲取屬性名
  • getValue  獲取屬性值

 

interface org.dom4j.Text

 

  • getText  獲取Text節點值

 

interface org.dom4j.CDATA

 

  • getText  獲取CDATA Section值

 

interface org.dom4j.Comment

 

  • getText  獲取注釋 

 

 

實例一:

//先加入dom4j.jar包 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**   
* @Title: TestDom4j.java
* @Package 
* @Description: 解析xml字符串
* @author 無處不在
* @date 2012-11-20 下午05:14:05
* @version V1.0   
*/
public class TestDom4j {

    public void readStringXml(String xml) {
        Document doc = null;
        try {

            // 讀取並解析XML文檔
            // SAXReader就是一個管道,用一個流的方式,把xml文件讀出來
            // 
            // SAXReader reader = new SAXReader(); //User.hbm.xml表示你要解析的xml文檔
            // Document document = reader.read(new File("User.hbm.xml"));
            // 下面的是通過解析xml字符串的
            doc = DocumentHelper.parseText(xml); // 將字符串轉為XML

            Element rootElt = doc.getRootElement(); // 獲取根節點
            System.out.println("根節點:" + rootElt.getName()); // 拿到根節點的名稱

            Iterator iter = rootElt.elementIterator("head"); // 獲取根節點下的子節點head

            // 遍歷head節點
            while (iter.hasNext()) {

                Element recordEle = (Element) iter.next();
                String title = recordEle.elementTextTrim("title"); // 拿到head節點下的子節點title值
                System.out.println("title:" + title);

                Iterator iters = recordEle.elementIterator("script"); // 獲取子節點head下的子節點script

                // 遍歷Header節點下的Response節點
                while (iters.hasNext()) {

                    Element itemEle = (Element) iters.next();

                    String username = itemEle.elementTextTrim("username"); // 拿到head下的子節點script下的字節點username的值
                    String password = itemEle.elementTextTrim("password");

                    System.out.println("username:" + username);
                    System.out.println("password:" + password);
                }
            }
            Iterator iterss = rootElt.elementIterator("body"); ///獲取根節點下的子節點body
            // 遍歷body節點
            while (iterss.hasNext()) {

                Element recordEless = (Element) iterss.next();
                String result = recordEless.elementTextTrim("result"); // 拿到body節點下的子節點result值
                System.out.println("result:" + result);

                Iterator itersElIterator = recordEless.elementIterator("form"); // 獲取子節點body下的子節點form
                // 遍歷Header節點下的Response節點
                while (itersElIterator.hasNext()) {

                    Element itemEle = (Element) itersElIterator.next();

                    String banlce = itemEle.elementTextTrim("banlce"); // 拿到body下的子節點form下的字節點banlce的值
                    String subID = itemEle.elementTextTrim("subID");

                    System.out.println("banlce:" + banlce);
                    System.out.println("subID:" + subID);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    /**
     * @description 將xml字符串轉換成map
     * @param xml
     * @return Map
     */
    public static Map readStringXmlOut(String xml) {
        Map map = new HashMap();
        Document doc = null;
        try {
            // 將字符串轉為XML
            doc = DocumentHelper.parseText(xml); 
            // 獲取根節點
            Element rootElt = doc.getRootElement(); 
            // 拿到根節點的名稱
            System.out.println("根節點:" + rootElt.getName()); 

            // 獲取根節點下的子節點head
            Iterator iter = rootElt.elementIterator("head"); 
            // 遍歷head節點
            while (iter.hasNext()) {

                Element recordEle = (Element) iter.next();
                // 拿到head節點下的子節點title值
                String title = recordEle.elementTextTrim("title"); 
                System.out.println("title:" + title);
                map.put("title", title);
                // 獲取子節點head下的子節點script
                Iterator iters = recordEle.elementIterator("script"); 
                // 遍歷Header節點下的Response節點
                while (iters.hasNext()) {
                    Element itemEle = (Element) iters.next();
                    // 拿到head下的子節點script下的字節點username的值
                    String username = itemEle.elementTextTrim("username"); 
                    String password = itemEle.elementTextTrim("password");

                    System.out.println("username:" + username);
                    System.out.println("password:" + password);
                    map.put("username", username);
                    map.put("password", password);
                }
            }

            //獲取根節點下的子節點body
            Iterator iterss = rootElt.elementIterator("body"); 
            // 遍歷body節點
            while (iterss.hasNext()) {
                Element recordEless = (Element) iterss.next();
                // 拿到body節點下的子節點result值
                String result = recordEless.elementTextTrim("result"); 
                System.out.println("result:" + result);
                // 獲取子節點body下的子節點form
                Iterator itersElIterator = recordEless.elementIterator("form"); 
                // 遍歷Header節點下的Response節點
                while (itersElIterator.hasNext()) {
                    Element itemEle = (Element) itersElIterator.next();
                    // 拿到body下的子節點form下的字節點banlce的值
                    String banlce = itemEle.elementTextTrim("banlce"); 
                    String subID = itemEle.elementTextTrim("subID");

                    System.out.println("banlce:" + banlce);
                    System.out.println("subID:" + subID);
                    map.put("result", result);
                    map.put("banlce", banlce);
                    map.put("subID", subID);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static void main(String[] args) {

        // 下面是需要解析的xml字符串例子
        String xmlString = "<html>" + "<head>" + "<title>dom4j解析一個例子</title>"
                + "<script>" + "<username>yangrong</username>"
                + "<password>123456</password>" + "</script>" + "</head>"
                + "<body>" + "<result>0</result>" + "<form>"
                + "<banlce>1000</banlce>" + "<subID>36242519880716</subID>"
                + "</form>" + "</body>" + "</html>";

        /*
         * Test2 test = new Test2(); test.readStringXml(xmlString);
         */
        Map map = readStringXmlOut(xmlString);
        Iterator iters = map.keySet().iterator();
        while (iters.hasNext()) {
            String key = iters.next().toString(); // 拿到鍵
            String val = map.get(key).toString(); // 拿到值
            System.out.println(key + "=" + val);
        }
    }

}

 

 

實例二:

/**
 * 解析包含有DB連接信息的XML文件
 * 格式必須符合如下規范:
 * 1. 最多三級,每級的node名稱自定義;
 * 2. 二級節點支持節點屬性,屬性將被視作子節點;
 * 3. CDATA必須包含在節點中,不能單獨出現。
 *
 * 示例1——三級顯示:
 * <db-connections>
 *         <connection>
 *            <name>DBTest</name>
 *            <jndi></jndi>
 *            <url>
 *                <![CDATA[jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=UTF8]]>
 *             </url>
 *            <driver>org.gjt.mm.mysql.Driver</driver>
 *             <user>test</user>
 *            <password>test2012</password>
 *            <max-active>10</max-active>
 *            <max-idle>10</max-idle>
 *            <min-idle>2</min-idle>
 *            <max-wait>10</max-wait>
 *            <validation-query>SELECT 1+1</validation-query>
 *         </connection>
 * </db-connections>
 *
 * 示例2——節點屬性:
 * <bookstore>
 *         <book category="cooking">
 *            <title lang="en">Everyday Italian</title>
 *            <author>Giada De Laurentiis</author>
 *            <year>2005</year>
 *            <price>30.00</price>
 *         </book>
 *
 *         <book category="children" title="Harry Potter" author="J K. Rowling" year="2005" price="$29.9"/>
 * </bookstore>

 *
 * @param configFile
 * @return
 * @throws Exception
 */
public static List<Map<String, String>> parseDBXML(String configFile) throws Exception {
    List<Map<String, String>> dbConnections = new ArrayList<Map<String, String>>();
    InputStream is = Parser.class.getResourceAsStream(configFile);
    SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(is);
    Element connections = document.getRootElement();

    Iterator<Element> rootIter = connections.elementIterator();
    while (rootIter.hasNext()) {
        Element connection = rootIter.next();
        Iterator<Element> childIter = connection.elementIterator();
        Map<String, String> connectionInfo = new HashMap<String, String>();
        List<Attribute> attributes = connection.attributes();
        for (int i = 0; i < attributes.size(); ++i) { // 添加節點屬性
            connectionInfo.put(attributes.get(i).getName(), attributes.get(i).getValue());
        }
        while (childIter.hasNext()) { // 添加子節點
            Element attr = childIter.next();
            connectionInfo.put(attr.getName().trim(), attr.getText().trim());
        }
        dbConnections.add(connectionInfo);
    }

    return dbConnections;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM