轉載地址:http://www.java3z.com/cwbwebhome/article/article2/2296.html?id=837
DOM4J是dom4j.org出品的一個開源XML解析包,它的網站中這樣定義:
Dom4j是一個易用的、開源的庫,用於XML,XPath和XSLT。它應用於Java平臺,採用了Java集合框架並完全支持DOM,SAX和JAXP。
在國內比較流行的是使用JDOM作爲解析器,兩者各擅其長,但DOM4J最大的特色是使用大量的接口,這也是它被認爲比JDOM靈活的主要原因。大師不是說過麼,“面向接口編程”。目前使用DOM4J的已經越來越多。如果你善於使用JDOM,不妨繼續用下去,只看看本篇文章作爲了解與比較,如果你正要採用一種解析器,不如就用DOM4J吧。
它的主要接口都在org.dom4j這個包裏定義:
Attribute
|
Attribute定義了XML的屬性
|
Branch
|
Branch爲能夠包含子節點的節點如XML元素(Element)和文檔(Docuemnts)定義了一個公共的行爲,
|
CDATA
|
CDATA 定義了XML CDATA 區域
|
CharacterData是一個標識接口,標識基於字符的節點。如CDATA,Comment, Text.
|
|
Comment
|
Comment 定義了XML註釋的行爲
|
Document
|
定義了XML文檔
|
DocumentType
|
DocumentType 定義XML DOCTYPE聲明
|
|
Element
|
Element定義XML 元素
|
ElementHandler
|
ElementHandler定義了 Element 對象的處理器
|
ElementPath
|
被 ElementHandler 使用,用於取得當前正在處理的路徑層次信息
|
Entity
|
Entity定義 XML entity
|
Node
|
Node爲所有的dom4j中XML節點定義了多態行爲
|
NodeFilter 定義了在dom4j節點中產生的一個濾鏡或謂詞的行爲(predicate)
|
|
ProcessingInstruction
|
ProcessingInstruction 定義 XML 處理指令.
|
Text
|
Text 定義XML 文本節點.
|
Visitor
|
Visitor 用於實現Visitor模式.
|
XPath
|
XPath 在分析一個字符串後會提供一個XPath 表達式
|
看名字大致就知道它們的涵義如何了。
- interface java.lang.Cloneable
- interface org.dom4j.Node
- interface org.dom4j.Attribute
- interface org.dom4j.Branch
- interface org.dom4j.Document
- interface org.dom4j.Element
- interface org.dom4j.CharacterData
- interface org.dom4j.CDATA
- interface org.dom4j.Comment
- interface org.dom4j.Text
- interface org.dom4j.DocumentType
- interface org.dom4j.Entity
- interface org.dom4j.ProcessingInstruction
// 從文件讀取XML,輸入文件名,返回XML文檔
public Document read(String fileName)
throws MalformedURLException, DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(new File(fileName));
return document;
}
|
其中,reader的read方法是重載的,可以從InputStream, File, Url等多種不同的源來讀取。得到的Document對象就帶表了整個XML。根據本人自己的經驗,讀取的字符編碼是按照XML文件頭定義的編碼來轉換。如果遇到亂碼問題,注意要把各處的編碼名稱保持一致即可。
public Element getRootElement(Document doc){
return doc.getRootElement();
}
|
3. 遍歷XML樹
// 枚舉所有子節點
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
}
|
2)遞歸
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....
}
}
}
|
3) Visitor模式
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();
}
}
|
5. 字符串與XML的轉換
// XML轉字符串
Document document = ...;
String text = document.asXML();
// 字符串轉XML
String text = <person> <name>James</name> </person>;
Document document = DocumentHelper.parseText(text);
|
6 用XSLT轉換XML
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;
}
|
7. 創建XML
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;
}
|
8. 文件輸出
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 );
}
|