版權聲明:
本文由冰雲完成,首發於CSDN,未經許可,不得使用於任何商業用途。
文中代碼部分引用自DOM4J文檔。
歡迎轉載,但請保持文章及版權聲明完整。
如需聯絡請發郵件:icecloud(AT)sina.com
|
Attribute定義了XML的屬性
|
|
Branch爲可以包含子節點的節點如XML元素(Element)和文檔(Docuemnts)定義了一個公共的行爲,
|
|
CDATA 定義了XML CDATA 區域
|
|
CharacterData是一個標識藉口,標識基於字符的節點。如CDATA,Comment, Text.
|
|
Comment 定義了XML註釋的行爲
|
|
定義了XML文檔
|
|
DocumentType 定義XML DOCTYPE聲明
|
|
Element定義XML 元素
|
|
ElementHandler定義了 Element 對象的處理器
|
|
被
ElementHandler 使用,用於取得當前正在處理的路徑層次信息
|
|
Entity定義 XML entity
|
|
Node爲全部的dom4j中XML節點定義了多態行爲
|
|
NodeFilter 定義了在dom4j節點中產生的一個濾鏡或謂詞的行爲(predicate)
|
|
ProcessingInstruction 定義 XML 處理指令.
|
|
Text 定義XML 文本節點.
|
|
Visitor 用於實現Visitor模式.
|
|
XPath 在分析一個字符串後會提供一個XPath 表達式
|
// 從文件讀取XML,輸入文件名,返回XML文檔
public Document read(String fileName)
throws MalformedURLException, DocumentException {
SAXReader reader =
new SAXReader();
Document document = reader.read(
new File(fileName));
return document;
}
|
public Element getRootElement(Document doc){
return doc.getRootElement();
}
|
// 枚舉全部子節點
for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
Element element = (Element) i.next();
// do something
}
// 枚舉名稱爲foo的節點
for ( Iterator i = root.elementIterator(foo); i.hasNext();) {
Element foo = (Element) i.next();
// do something
}
// 枚舉屬性
for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {
Attribute attribute = (Attribute) i.next();
// do something
}
|
public
void treeWalk() {
treeWalk(getRootElement());
}
public
void treeWalk(Element element) {
for (
int i = 0, size = element.nodeCount(); i < size; i++) {
Node node = element.node(i);
if (node
instanceof Element) {
treeWalk((Element) node);
}
else { // do something....
}
}
}
|
public
class MyVisitor
extends VisitorSupport {
public
void visit(Element element){
System.out.println(element.getName());
}
public
void visit(Attribute attr){
System.out.println(attr.getName());
}
}
調用: root.accept(new MyVisitor())
|
public
void bar(Document document) {
List list = document.selectNodes( //foo/bar );
Node node = document.selectSingleNode(//foo/bar/author);
String name = node.valueOf( @name );
}
|
public
void findLinks(Document document)
throws DocumentException {
List list = document.selectNodes( //a/@href );
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
Attribute attribute = (Attribute) iter.next();
String url = attribute.getValue();
}
}
|
// XML轉字符串
Document document = ...;
String text = document.asXML();
// 字符串轉XML
String text = James ;
Document document = DocumentHelper.parseText(text);
|
public Document styleDocument(
Document document,
String stylesheet
)
throws Exception {
// load the transformer using JAXP
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(
new StreamSource( stylesheet )
);
// now lets style the given document
DocumentSource source =
new DocumentSource( document );
DocumentResult result =
new DocumentResult();
transformer.transform( source, result );
// return the transformed document
Document transformedDoc = result.getDocument();
return transformedDoc;
}
|
public Document createDocument() {
Document document = DocumentHelper.createDocument();
Element root = document.addElement(root);
Element author1 =
root
.addElement(author)
.addAttribute(name, James)
.addAttribute(location, UK)
.addText(James Strachan);
Element author2 =
root
.addElement(author)
.addAttribute(name, Bob)
.addAttribute(location, US)
.addText(Bob McWhirter);
return document;
}
|
FileWriter out =
new FileWriter( foo.xml );
document.write(out);
|
public
void write(Document document)
throws IOException {
// 指定文件
XMLWriter writer =
new XMLWriter(
new FileWriter( output.xml )
);
writer.write( document );
writer.close();
// 美化格式
OutputFormat format = OutputFormat.createPrettyPrint();
writer =
new XMLWriter( System.out, format );
writer.write( document );
// 縮減格式
format = OutputFormat.createCompactFormat();
writer =
new XMLWriter( System.out, format );
writer.write( document );
}
|
holen.xml
|
<?xml version="1.0" encoding="UTF-8"?>
<!--This is a test for dom4j, holen, 2004.9.11-->
O'Reilly
|
|
/**
* 創建一個XML文檔,文檔名由輸入屬性決定
*
@param filename 需創建的文件名
*
@return 返回操做結果, 0表失敗, 1表成功
*/
public
int createXMLFile(String filename){
/** 返回操做結果, 0表失敗, 1表成功 */
int returnValue = 0;
/** 創建document對象 */
Document document = DocumentHelper.createDocument();
/** 創建XML文檔的根books */
Element booksElement = document.addElement("books");
/** 加入一行註釋 */
booksElement.addComment("This is a test for dom4j, holen, 2004.9.11");
/** 加入第一個book節點 */
Element bookElement = booksElement.addElement("book");
/** 加入show屬性內容 */
bookElement.addAttribute("show","yes");
/** 加入title節點 */
Element titleElement = bookElement.addElement("title");
/** 爲title設置內容 */
titleElement.setText("Dom4j Tutorials");
/** 相似的完成後兩個book */
bookElement = booksElement.addElement("book");
bookElement.addAttribute("show","yes");
titleElement = bookElement.addElement("title");
titleElement.setText("Lucene Studing");
bookElement = booksElement.addElement("book");
bookElement.addAttribute("show","no");
titleElement = bookElement.addElement("title");
titleElement.setText("Lucene in Action");
/** 加入owner節點 */
Element ownerElement = booksElement.addElement("owner");
ownerElement.setText("O'Reilly");
try{
/** 將document中的內容寫入文件中 */
XMLWriter writer =
new XMLWriter(
new FileWriter(
new File(filename)));
writer.write(document);
writer.close();
/** 執行成功,需返回1 */
returnValue = 1;
}
catch(Exception ex){
ex.printStackTrace();
}
return returnValue;
}
|
|
<?xml version="1.0" encoding="UTF-8"?>
<!--This is a test for dom4j, holen, 2004.9.11-->O'Reilly
|
|
/**
* 修改XML文件中內容,並另存爲一個新文件
* 重點掌握dom4j中如何添加節點,修改節點,刪除節點
*
@param filename 修改對象文件
*
@param newfilename 修改後另存爲該文件
*
@return 返回操做結果, 0表失敗, 1表成功
*/
public
int ModiXMLFile(String filename,String newfilename){
int returnValue = 0;
try{
SAXReader saxReader =
new SAXReader();
Document document = saxReader.read(
new File(filename));
/** 修改內容之一: 若是book節點中show屬性的內容爲yes,則修改爲no */
/** 先用xpath查找對象 */
List list = document.selectNodes("/books/book/@show" );
Iterator iter = list.iterator();
while(iter.hasNext()){
Attribute attribute = (Attribute)iter.next();
if(attribute.getValue().equals("yes")){
attribute.setValue("no");
}
}
/**
* 修改內容之二: 把owner項內容改成Tshinghua
* 並在owner節點中加入date節點,date節點的內容爲2004-09-11,還爲date節點添加一個屬性type
*/
list = document.selectNodes("/books/owner" );
iter = list.iterator();
if(iter.hasNext()){
Element ownerElement = (Element)iter.next();
ownerElement.setText("Tshinghua");
Element dateElement = ownerElement.addElement("date");
dateElement.setText("2004-09-11");
dateElement.addAttribute("type","Gregorian calendar");
}
/** 修改內容之三: 若title內容爲Dom4j Tutorials,則刪除該節點 */
list = document.selectNodes("/books/book");
iter = list.iterator();
while(iter.hasNext()){
Element bookElement = (Element)iter.next();
Iterator iterator = bookElement.elementIterator("title");
while(iterator.hasNext()){
Element titleElement=(Element)iterator.next();
if(titleElement.getText().equals("Dom4j Tutorials")){
bookElement.remove(titleElement);
}
}
}
try{
/** 將document中的內容寫入文件中 */
XMLWriter writer =
new XMLWriter(
new FileWriter(
new File(newfilename)));
writer.write(document);
writer.close();
/** 執行成功,需返回1 */
returnValue = 1;
}
catch(Exception ex){
ex.printStackTrace();
}
}
catch(Exception ex){
ex.printStackTrace();
}
return returnValue;
}
|
|
/**
* 格式化XML文檔,並解決中文問題
*
@param filename
*
@return
*/
public
int formatXMLFile(String filename){
int returnValue = 0;
try{
SAXReader saxReader =
new SAXReader();
Document document = saxReader.read(
new File(filename));
XMLWriter writer =
null;
/** 格式化輸出,類型IE瀏覽同樣 */
OutputFormat format = OutputFormat.createPrettyPrint();
/** 指定XML編碼 */
format.setEncoding("GBK");
writer=
new XMLWriter(
new FileWriter(
new File(filename)),format);
writer.write(document);
writer.close();
/** 執行成功,需返回1 */
returnValue = 1;
}
catch(Exception ex){
ex.printStackTrace();
}
return returnValue;
}
|
Dom4jDemo.java
|
package com.holen.dom4j;
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
*
@author Holen Chen</
|