本文實例講述了java基于dom4j包實現對XML解析的方法。分享給大家供大家參考,具體如下:
本例中的xml文件內容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<? xml version = "1.0" encoding = "UTF-8" ?> <!-- Copyright 難免有錯 這是注釋--> <自定義的> <!-- iloveyou --> <你喜歡的名字就好> < who a = "i" ></ who > < dowhat b = "love" ></ dowhat > < whom c = "you" ></ whom > </你喜歡的名字就好> <!-- youhateme --> <好吧> < who a = "you" ></ who > < dowhat b = "hate" ></ dowhat > < whom c = "me" ></ whom > </好吧> </自定義的> |
Java解析XML代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
package xmlreadtest; import java.io.File; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class Xmlreadtest { public static void main(String[] args) throws DocumentException { //創建一個readxml對象的實例 Readxml re = new Readxml(); //調用readexmldata方法 re.readxmldata( "你喜歡的名字就好" ); re.readxmldata( "好吧" ); } } /** * 2015年8月31日 * @author 難免有錯 * */ class Readxml { //參數為xml文件的子元素 如本例中test.xml文件的的"你喜歡的名字就好" public void readxmldata(String str) throws DocumentException { //創建SAXReader對象 SAXReader reader = new SAXReader(); org.dom4j.Document dcfile = reader.read( new File( "test.xml" )); //獲得xml文件的root節點 Element root = dcfile.getRootElement(); //獲取名字為指定名稱子元素 Element e_interface = root.element(str); //傳入參數 String ewho = (String) e_interface.element( "who" ).attribute( 0 ).getData(); String edo = (String) e_interface.element( "dowhat" ).attribute( 0 ).getData(); String ewhom = (String) e_interface.element( "whom" ).attribute( 0 ).getData(); System.out.println(ewho+edo+ewhom); } } |
程序運行結果:
1
2
|
iloveyou youhateme |
注:本例只是個簡單的RAX方式解析
希望本文所述對大家java程序設計有所幫助。