1. 程式人生 > >Dom4j中getStringValue()和getText()用法和區別

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

這兩個方法的左右都是獲取文字,但是區別是:
getText(方法是)獲取當前節點的文字內容。是當前節點.如果當前節點是一個element元素,那返回值就是null.
而getStringValue()則是獲取當前節點的子孫節點中所有文字內容連線成的字串.
也就是說,是包括getText()的.
先看一下例項:
一個簡單的xml架構文件如下,其他輔助檔案自己不全哈.

<books>
   <book>
       <title>平凡的世界</title>
   </book>
   <book>
       <title
>
老人與海</title> </book> </books>

讀取和解析:

public static void main(String[] args) {
        File file =new File("");//獲得當前工作路徑,讀取xml文件

        String xmlPath=file.getCanonicalPath() ++"\\config\\books.xml";//獲得路徑
        File xmlFile=new File(xmlPath);
        //用SAXReader進行解析
        SAXReader reader = new
SAXReader(); Document doc = reader.read(xmlFile); //選擇books節點,進行試驗 Element root = doc.getRootElement(); System.out.println("getStringValue()===" + root.getStringValue()); System.out.println("getText()===" + root.getText()); }

結果就是:
getText()===
getStringValue()===平凡的世界老人與海

做個筆記,以後用到的時候方便.與君共享.歡迎指點.