//導入必要的包
import
org.dom4j.Document
;
//Document文檔類
import org.
dom4j.
Element
//元素節點類
import
org.dom4j.QName
;
//一個對元素名字的封裝類
import
org.dom4j.io.SAXReader
;
//sax讀取類
import
org.dom4j.io.XMLWriter
;
//xml寫入類
import
org.dom4j.io.OutputFormat
;
//輸出格式
//讀入xml文件
String fileName
=
"*****"
;
InputStream input
=
new
FileInputStream
(fileName
)
; SAXReader reader
=
new SAXReader
(
)
;
Document doc
= reader.
read
(input
)
;<span id
=
"more-185"
></span
>
//操作Document文檔
//1,利用xpath表達式進行查詢
//最常用
List
<
;Document or Element
>
;
selectNodes
(
String xpathExpression
)
;
//第二個參數comparisonXPathExpression代表排序的xpath
List
<
;Document or Element
>
; selectNodes
(
String xpathExpression,
String comparisonXPathExpression
)
; 返回
List數據類型,可以利用iterator進行遍歷,然后
Element轉型
//指返回第一匹配xpath的結點 Node selectSingleNode
(
String
xpathExpression
)
;
//返回結點所有的子節點
List elements
(
)
;
//2,獲取節點的內容--Element
//獲得節點的元素的text文本<name>yaron</name>,將返回yaron
String getText
(
)
;
void setText
(
String value
)
;
//返回節點的屬性值
String attributeValue
(
String name
)
;
void setAttributeValue
(
String name,
String value
)
;
//獲得標簽本身的名稱
String getName
(
)
;
void setName
(
String name
)
;
//3,復制節點
Element createCopy
(
)
;
//4,獲得父節點
Element getParent
(
)
;
//5,保存xml文件
//獲得寫入模式 OutputFormat format
= OutputFormat.
createPrettyPrint
(
)
;
FileWriter fileOutput
=
new
FileWriter
(
new
File
(fileName
)
)
; XMLWriter output
=
new XMLWriter
(fileOutput,format
)
;
//doc的類型為Document; output.
write
(doc
)
; output.
close
(
)
;