Dom4j学习

来源:百度文库 编辑:神马文学网 时间:2024/04/28 10:12:43
Dom4j是一个易用的、开源的库,用于XML,XPath和XSLT。它应用于Java平台,采用了Java集合框架并完全支持DOM,SAX和JAXP。
它的主要接口都在org.dom4j这个包里定义:
Attribute
Attribute定义了XML的属性
Branch
Branch为能够包含子节点的节点如XML元素(Element)和文档(Docuemnts)定义了一个公共的行为,
CDATA
CDATA 定义了XML CDATA 区域
CharacterData
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
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
1.              读取并解析XML文档:
读写XML文档主要依赖于org.dom4j.io包,其中提供DOMReader和SAXReader两类不同方式,而调用方式是一样的。这就是依靠接口的好处。
import java.net.URL;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.io.SAXReader;public class Foo { public Document parse(URL url) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(url); return document; }}其中,reader的read方法是重载的,可以从InputStream, File, Url等多种不同的源来读取。得到的Document对象就带表了整个XML。
根据本人自己的经验,读取的字符编码是按照XML文件头定义的编码来转换。如果遇到乱码问题,注意要把各处的编码名称保持一致即可。
2、使用枚举
一个document可以通过标准的jave Iterators 来访问,例如
public void bar(Document document) throws DocumentException { Element root = document.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 } }
3、使用XPath
在don4j中XPath通过Document或树上的任何节点(属性、元素或指令)来表示,因此可根号document中的一行简单代码
来进行复杂的操作。例如:
//访问一个节点,可直接用XPath选择
public void bar(Document document) { List list = document.selectNodes( "//foo/bar" ); Node node = document.selectSingleNode( "//foo/bar/author" ); String name = node.valueOf( "@name" ); }
//查找XHTML文档中所有的超链接 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(); } }4、快速循环如果访问一个大的XML文献树,为避免每次循环时都要创建一个枚举对象,可采用快速循环的方式,例如: public void treeWalk(Document document) { treeWalk( document.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.... } } }5、创建新的XML文献
在dom4j中常常需要建立一个新的document,举例说明:
import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;public class Foo { 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; }}6、把document写入文件中通过write()方法可以方便的将一个Document或任意节点写入到文件中, FileWriter out = new FileWriter( "foo.xml" ); document.write( out );如果要改变输出的格式,例如较紧凑形式的打印,可采用XMLWriter类,import org.dom4j.Document;import org.dom4j.io.OutputFormat;import org.dom4j.io.XMLWriter;public class Foo { public void write(Document document) throws IOException { // 输出到文件 XMLWriter writer = new XMLWriter( new FileWriter( "output.xml" ) ); writer.write( document ); writer.close(); // Pretty print the document to System.out OutputFormat format = OutputFormat.createPrettyPrint(); writer = new XMLWriter( System.out, format ); writer.write( document ); // Compact format to System.out format = OutputFormat.createCompactFormat(); writer = new XMLWriter( System.out, format ); writer.write( document ); }}7、与字符串的转换
//可通过asXML()方法将一个Document或 其他节点(属性或元素)转换为XML文本,
Document document = ...; String text = document.asXML();
//可通过helper 方法DocumentHelper.parseText()对XML文本进行解析,转换为Document,
String text = " James "; Document document = DocumentHelper.parseText(text);
8、Styling a Document with XSLT
Applying XSLT on a Document is quite straightforward using theJAXP API from Sun. This allows you to work against any XSLT engine such as Xalan or SAXON. Here is an example of using JAXP to create a transformer and then applying it to a Document.
import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import org.dom4j.Document;import org.dom4j.io.DocumentResult;import org.dom4j.io.DocumentSource;public class Foo { 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; }}