首頁 後端開發 XML/RSS教程 分享一個xml字串透過dom4j解析的方法

分享一個xml字串透過dom4j解析的方法

May 04, 2017 pm 03:46 PM

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

实例一:

  1 //先加入dom4j.jar包   2 import java.util.HashMap;  3 import java.util.Iterator;  4 import java.util.Map;  5   6 import org.dom4j.Document;  7 import org.dom4j.DocumentException;  8 import org.dom4j.DocumentHelper;  9 import org.dom4j.Element; 10  11 /**    12 * @Title: TestDom4j.java 13 * @Package 
 14 * @Description: 解析xml字符串 15 * @author 无处不在 16 * @date 2012-11-20 下午05:14:05 17 * @version V1.0   
 18 */ 19 public class TestDom4j { 20  21     public void readStringXml(String xml) { 22         Document doc = null; 23         try { 24  25             // 读取并解析XML文档 26             // SAXReader就是一个管道,用一个流的方式,把xml文件读出来 27             //  28             // SAXReader reader = new SAXReader(); //User.hbm.xml表示你要解析的xml文档 29             // Document document = reader.read(new File("User.hbm.xml")); 30             // 下面的是通过解析xml字符串的 31             doc = DocumentHelper.parseText(xml); // 将字符串转为XML 32  33             Element rootElt = doc.getRootElement(); // 获取根节点 34             System.out.println("根节点:" + rootElt.getName()); // 拿到根节点的名称 35  36             Iterator iter = rootElt.elementIterator("head"); // 获取根节点下的子节点head 37  38             // 遍历head节点 39             while (iter.hasNext()) { 40  41                 Element recordEle = (Element) iter.next(); 42                 String title = recordEle.elementTextTrim("title"); // 拿到head节点下的子节点title值 43                 System.out.println("title:" + title); 44  45                 Iterator iters = recordEle.elementIterator("script"); // 获取子节点head下的子节点script 46  47                 // 遍历Header节点下的Response节点 48                 while (iters.hasNext()) { 49  50                     Element itemEle = (Element) iters.next(); 51  52                     String username = itemEle.elementTextTrim("username"); // 拿到head下的子节点script下的字节点username的值 53                     String password = itemEle.elementTextTrim("password"); 54  55                     System.out.println("username:" + username); 56                     System.out.println("password:" + password); 57                 } 58             } 59             Iterator iterss = rootElt.elementIterator("body"); ///获取根节点下的子节点body 60             // 遍历body节点 61             while (iterss.hasNext()) { 62  63                 Element recordEless = (Element) iterss.next(); 64                 String result = recordEless.elementTextTrim("result"); // 拿到body节点下的子节点result值 65                 System.out.println("result:" + result); 66  67                 Iterator itersElIterator = recordEless.elementIterator("form"); // 获取子节点body下的子节点form 68                 // 遍历Header节点下的Response节点 69                 while (itersElIterator.hasNext()) { 70  71                     Element itemEle = (Element) itersElIterator.next(); 72  73                     String banlce = itemEle.elementTextTrim("banlce"); // 拿到body下的子节点form下的字节点banlce的值 74                     String subID = itemEle.elementTextTrim("subID"); 75  76                     System.out.println("banlce:" + banlce); 77                     System.out.println("subID:" + subID); 78                 } 79             } 80         } catch (DocumentException e) { 81             e.printStackTrace(); 82  83         } catch (Exception e) { 84             e.printStackTrace(); 85  86         } 87     } 88  89     /** 90      * @description 将xml字符串转换成map 91      * @param xml 92      * @return Map 93      */ 94     public static Map readStringXmlOut(String xml) { 95         Map map = new HashMap(); 96         Document doc = null; 97         try { 98             // 将字符串转为XML 99             doc = DocumentHelper.parseText(xml); 
100             // 获取根节点101             Element rootElt = doc.getRootElement(); 
102             // 拿到根节点的名称103             System.out.println("根节点:" + rootElt.getName()); 
104 105             // 获取根节点下的子节点head106             Iterator iter = rootElt.elementIterator("head"); 
107             // 遍历head节点108             while (iter.hasNext()) {109 110                 Element recordEle = (Element) iter.next();111                 // 拿到head节点下的子节点title值112                 String title = recordEle.elementTextTrim("title"); 
113                 System.out.println("title:" + title);114                 map.put("title", title);115                 // 获取子节点head下的子节点script116                 Iterator iters = recordEle.elementIterator("script"); 
117                 // 遍历Header节点下的Response节点118                 while (iters.hasNext()) {119                     Element itemEle = (Element) iters.next();120                     // 拿到head下的子节点script下的字节点username的值121                     String username = itemEle.elementTextTrim("username"); 
122                     String password = itemEle.elementTextTrim("password");123 124                     System.out.println("username:" + username);125                     System.out.println("password:" + password);126                     map.put("username", username);127                     map.put("password", password);128                 }129             }130 131             //获取根节点下的子节点body132             Iterator iterss = rootElt.elementIterator("body"); 
133             // 遍历body节点134             while (iterss.hasNext()) {135                 Element recordEless = (Element) iterss.next();136                 // 拿到body节点下的子节点result值137                 String result = recordEless.elementTextTrim("result"); 
138                 System.out.println("result:" + result);139                 // 获取子节点body下的子节点form140                 Iterator itersElIterator = recordEless.elementIterator("form"); 
141                 // 遍历Header节点下的Response节点142                 while (itersElIterator.hasNext()) {143                     Element itemEle = (Element) itersElIterator.next();144                     // 拿到body下的子节点form下的字节点banlce的值145                     String banlce = itemEle.elementTextTrim("banlce"); 
146                     String subID = itemEle.elementTextTrim("subID");147 148                     System.out.println("banlce:" + banlce);149                     System.out.println("subID:" + subID);150                     map.put("result", result);151                     map.put("banlce", banlce);152                     map.put("subID", subID);153                 }154             }155         } catch (DocumentException e) {156             e.printStackTrace();157         } catch (Exception e) {158             e.printStackTrace();159         }160         return map;161     }162 163     public static void main(String[] args) {164 165         // 下面是需要解析的xml字符串例子166         String xmlString = "<html>" + "<head>" + "<title>dom4j解析一个例子</title>"167                 + "<script>" + "<username>yangrong</username>"168                 + "<password>123456</password>" + "</script>" + "</head>"169                 + "<body>" + "<result>0</result>" + "<form>"170                 + "<banlce>1000</banlce>" + "<subID>36242519880716</subID>"171                 + "</form>" + "</body>" + "</html>";172 173         /*174          * Test2 test = new Test2(); test.readStringXml(xmlString);175          */176         Map map = readStringXmlOut(xmlString);177         Iterator iters = map.keySet().iterator();178         while (iters.hasNext()) {179             String key = iters.next().toString(); // 拿到键180             String val = map.get(key).toString(); // 拿到值181             System.out.println(key + "=" + val);182         }183     }184 185 }实例二:
登入後複製
 1 /** 2  * 解析包含有DB连接信息的XML文件 3  * 格式必须符合如下规范: 4  * 1. 最多三级,每级的node名称自定义; 5  * 2. 二级节点支持节点属性,属性将被视作子节点; 6  * 3. CDATA必须包含在节点中,不能单独出现。 7  * 8  * 示例1——三级显示: 9  * <db-connections>10  *         <connection>11  *            <name>DBTest</name>12  *            <jndi></jndi>13  *            <url>14  *                <![CDATA[jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=UTF8]]>15  *             </url>16  *            <driver>org.gjt.mm.mysql.Driver</driver>17  *             <user>test</user>18  *            <password>test2012</password>19  *            <max-active>10</max-active>20  *            <max-idle>10</max-idle>21  *            <min-idle>2</min-idle>22  *            <max-wait>10</max-wait>23  *            <validation-query>SELECT 1+1</validation-query>24  *         </connection>25  * </db-connections>26  *27  * 示例2——节点属性:28  * <bookstore>29  *         <book category="cooking">30  *            <title lang="en">Everyday Italian</title>31  *            <author>Giada De Laurentiis</author>32  *            <year>2005</year>33  *            <price>30.00</price>34  *         </book>35  *36  *         <book category="children" title="Harry Potter" author="J K. Rowling" year="2005" price="$29.9"/>37  * </bookstore>38  *39  * @param configFile40  * @return41  * @throws Exception42  */43 public static List<Map<String, String>> parseDBXML(String configFile) throws Exception {44     List<Map<String, String>> dbConnections = new ArrayList<Map<String, String>>();45     InputStream is = Parser.class.getResourceAsStream(configFile);46     SAXReader saxReader = new SAXReader();47     Document document = saxReader.read(is);48     Element connections = document.getRootElement();49 50     Iterator<Element> rootIter = connections.elementIterator();51     while (rootIter.hasNext()) {52         Element connection = rootIter.next();53         Iterator<Element> childIter = connection.elementIterator();54         Map<String, String> connectionInfo = new HashMap<String, String>();55         List<Attribute> attributes = connection.attributes();56         for (int i = 0; i < attributes.size(); ++i) { // 添加节点属性57             connectionInfo.put(attributes.get(i).getName(), attributes.get(i).getValue());58         }59         while (childIter.hasNext()) { // 添加子节点60             Element attr = childIter.next();61             connectionInfo.put(attr.getName().trim(), attr.getText().trim());62         }63         dbConnections.add(connectionInfo);64     }65 66     return dbConnections;67 }
登入後複製

【相关推荐】

1. XML免费视频教程 

2. XML技术手册

3. 布尔教育燕十八XML视频教程

以上是分享一個xml字串透過dom4j解析的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Golang字串是否以指定字元結尾的判斷方法 Golang字串是否以指定字元結尾的判斷方法 Mar 12, 2024 pm 04:48 PM

標題:Golang中判斷字串是否以指定字元結尾的方法在Go語言中,有時候我們需要判斷一個字串是否以特定的字元結尾,這在處理字串時十分常見。本文將介紹如何使用Go語言來實現這項功能,同時提供程式碼範例供大家參考。首先,讓我們來看看Golang中如何判斷一個字串是否以指定字元結尾的方法。 Golang中的字串可以透過索引來取得其中的字符,而字串的長度可

怎麼重複字串_python重複字串教程 怎麼重複字串_python重複字串教程 Apr 02, 2024 pm 03:58 PM

1.先開啟pycharm,進入到pycharm首頁。 2.然後新建python腳本,右鍵--點選new--點選pythonfile。 3.輸入一段字串,代碼:s="-"。 4.接著需要把字串裡面的符號重複20次,代碼:s1=s*20。5、輸入列印輸出代碼,代碼:print(s1)。 6.最後運行腳本,在最底部會看到我們的回傳值:-就重複了20次。

PHP中int型別轉字串的方法詳解 PHP中int型別轉字串的方法詳解 Mar 26, 2024 am 11:45 AM

PHP中int型別轉字串的方法詳解在PHP開發中,常會遇到將int型別轉換為字串型別的需求。這種轉換可以透過多種方式實現,本文將詳細介紹幾種常用的方法,並附帶具體的程式碼範例來幫助讀者更好地理解。一、使用PHP內建函數strval()PHP提供了一個內建函數strval(),可以將不同類型的變數轉換為字串類型。當我們需要將int型別轉換為字串型別時,

如何在Go語言中截取字串 如何在Go語言中截取字串 Mar 13, 2024 am 08:33 AM

Go語言是一種強大且靈活的程式語言,它提供了豐富的字串處理功能,包括字串截取。在Go語言中,我們可以使用切片(slice)來截取字串。接下來,將詳細介紹如何在Go語言中截取字串,並附上具體的程式碼範例。一、使用切片截取字串在Go語言中,可以使用切片表達式來截取字串的一部分。切片表達式的語法如下:slice:=str[start:end]其中,s

Golang中如何檢查字串是否以特定字元開頭? Golang中如何檢查字串是否以特定字元開頭? Mar 12, 2024 pm 09:42 PM

Golang中如何檢查字串是否以特定字元開頭?在使用Golang程式設計時,經常會遇到需要檢查一個字串是否以特定字元開頭的情況。針對這項需求,我們可以使用Golang中的strings套件所提供的函數來實現。接下來將詳細介紹如何使用Golang檢查字串是否以特定字元開頭,並附上具體的程式碼範例。在Golang中,我們可以使用strings套件中的HasPrefix

如何使用 PHP 函數處理 XML 資料? 如何使用 PHP 函數處理 XML 資料? May 05, 2024 am 09:15 AM

使用PHPXML函數處理XML資料:解析XML資料:simplexml_load_file()和simplexml_load_string()載入XML檔案或字串。存取XML資料:利用SimpleXML物件的屬性和方法來取得元素名稱、屬性值和子元素。修改XML資料:使用addChild()和addAttribute()方法新增元素和屬性。序列化XML資料:asXML()方法將SimpleXML物件轉換為XML字串。實戰案例:解析產品饋送XML,提取產品信息,轉換並將其儲存到資料庫中。

PHP字串操作:去除多餘逗號,保留唯一逗號實作技巧 PHP字串操作:去除多餘逗號,保留唯一逗號實作技巧 Mar 28, 2024 pm 03:02 PM

PHP字串操作:去除多餘逗號,保留唯一逗號實作技巧在PHP開發中,字串處理是一個非常常見的需求。有時候我們需要對字串進行處理,去除多餘的逗號,保留唯一的逗號。在這篇文章中,我將介紹一種實作技巧,並提供具體的程式碼範例。首先,我們來看一個常見的需求:假設我們有一個包含多個逗號的字串,我們需要去除多餘的逗號,只保留唯一的逗號。例如,將"apple,ba

Golang 字串修改詳解:動態調整與可變性 Golang 字串修改詳解:動態調整與可變性 Apr 08, 2024 pm 03:27 PM

GoLang中的字串雖然不可變,但可透過以下技術動態修改:使用字串連接符號連接字串。使用字串格式化建立新字串。修改字串底層位元組切片。使用第三方庫提供的可變字串類型。

See all articles