Dom4j中getStringValue()和getText()用法的區別


這兩個方法都是獲取文本的,區別是:

getText()-----獲取當前節點的文本內容,如果當前節點下是一個element元素,那返回的就是null.

getStringValue------獲取當前節點的子孫節點中的所有文本內容連接成的字符串.

 

例子:

 1 package XML;
 2 
 3 import org.dom4j.Document;
 4 import org.dom4j.DocumentException;
 5 import org.dom4j.Element;
 6 import org.dom4j.io.SAXReader;
 7 
 8 public class Test5 {
 9 
10     public static void main(String[] args) throws DocumentException {
11         SAXReader reader=new SAXReader();
12         Document doc = reader.read("config/book.xml");
13         Element root = doc.getRootElement();
14         //獲取當前節點的子孫節點中的所有文本內容連接成的字符串.
15         System.out.println("getStringValue:"+root.getStringValue());
16         //獲取當前節點的文本內容,如果當前節點下是一個element元素,那返回的就是null.
17         System.out.println("getText:"+root.getText());
18         //可去掉文本內容的空格
19         System.out.println("getTextTrim:"+root.getTextTrim());
20     }
21 
22 }

//config/book.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <books>
 3     hahahah
 4     <number>3</number>
 5     <book>
 6         <name>紅樓夢</name>
 7         <price>28</price>
 8         <publishing_company>大象出版社</publishing_company>
 9     </book>
10     <book>
11         <name>西游記</name>
12         <price>56</price>
13         <publishing_company>西南出版社</publishing_company>
14     </book>
15     <book>
16         <name>水滸傳</name>
17         <price>66</price>
18         <publishing_company>天津出版社</publishing_company>
19     </book>
20 </books>

結果:

 


免責聲明!

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



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