转载地址: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 );
}
|