- 论坛徽章:
- 0
|
Dom4j 使用心得
Dom4j 使用心得
DOM4J 是 dom4j.org 出品的一个开源 XML 解析包,它的网站中这样定义:
Dom4j is an easy to use, open source library for working with XML, XPath and XSLT on the Java platform using the Java Collections Framework and with full support for DOM, SAX and JAXP.
Dom4j 是一个易用的、开源的库,用于 XML , XPath 和 XSLT 。它应用于 Java 平台,采用了 Java 集合框架并完全支持 DOM , SAX 和 JAXP 。
Dom4j.jar
包括 dom4j 类和 XPath 引擎,但是不含 SAX 与 DOM 接口。最好使用 1.5 的版本 , 有两个包文件 , dom4j-1.5.jar 和 dom4j-full.jar ,目前 1.6 的还不稳定。下载网址:
http://sourceforge.net/projects/dom4j
。
它的主要接口都在 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 表达式
1.读取并解析XML文档:
读写XML文档主要依赖于org.dom4j.io包,其中提供DOMReader和SAXReader两类不同方式,而调用方式是一样的。这就是依靠接口的好处。
// 从文件读取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文件头定义的编码来转换。如果遇到乱码问题,注意要把各处的编码名称保持一致即可。
2. 取得Root节点
读取后的第二步,就是得到Root节点。熟悉XML的人都知道,一切XML分析都是从Root元素开始的。
public Element getRootElement(Document doc)
{
return doc.getRootElement();
}
3. 遍历XML树
DOM4J提供至少3种遍历节点的方法:
1) 枚举(Iterator)
// 枚举所有子节点
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)递归
递归也可以采用Iterator作为枚举手段,但文档中提供了另外的做法
public void treeWalk()
{
treeWalk(getRootElement());
}
public void treeWalk(Element element)
{
for (int i = 0, size = element.nodeCount(); i
{ Node node = element.node(i);
if (node instanceof Element)
{ treeWalk((Element) node); }
else
{ // do something
.
} }}
4. XPath支持
DOM4J对XPath有良好的支持,如访问一个节点,可直接用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(); } }
5. 字符串与XML的转换
有时候经常要用到字符串转换为XML或反之,
// XML转字符串
Document document =
;
String text = document.asXML();// 字符串转XML
String text = James ;
Document document = DocumentHelper.parseText(text);
7. 创建XML
一般创建XML是写文件前的工作,这就像StringBuffer一样容易。
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 Strachn);
Element author2 = root .addElement(author) .addAttribute(name, Bob) .addAttribute(location, US) .addText(Bob McWhirter);
return document;
如果你想改变输出的格式,比如美化输出或缩减格式,可以用XMLWriter类
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 ); }
一、 使用
1、创建XML文档
dom4j创建xmlgenerateDocument()需要以下四步:创建文档、添加根元素、添加子元素、添加元素内容、写XML文件。
使用的类有org.dom4j.Document,org.dom4j.DocumentHelper,
org.dom4j.Element 类。
代码如下:
import org.dom4j.Document; //导入dom4j API 类
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Attribute;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.dom4j.io.SAXReader;
import java.io.*;
import java.util.List;
import java.util.Iterator;
class Rt {
public Document generateDocument() {
//使用DocumentHelper 类创建一个文档实例。DocumentHelper 是生成XML 文档节点的dom4j API 工厂类。
Document document = DocumentHelper.createDocument();
//使用addElement() 方法创建根元素catalog 。addElement() 用于向XML 文档中增加元素。
Element catalogElement = document.addElement("catalog");
//在catalog 元素中使用addComment() 方法添加注释“An XML catalog”。
catalogElement.addComment("An XML Catalog");
//在catalog 元素中使用addProcessingInstruction() 方法增加一个处理指令。
catalogElement.addProcessingInstruction("target","text");
//在catalog 元素中使用addElement() 方法增加journal 元素。
Element journalElement = catalogElement.addElement("journal");
//使用addAttribute() 方法向journal 元素添加title 和publisher 属性
journalElement.addAttribute("title", "XML Zone");
journalElement.addAttribute("publisher", "IBM developerWorks");
//向journal 元素中添加article 元素,使用addAttribute()方法向article元素添加level,date属性
Element articleElement=journalElement.addElement("article");
articleElement.addAttribute("level", "Intermediate");
articleElement.addAttribute("date", "December-2001");
//向article元素中添加title元素
Element titleElement=articleElement.addElement("title");
//使用setText() 方法设置article 元素的文本
titleElement.setText("Java configuration with XML Schema");
//向article元素中添加author元素
Element authorElement=articleElement.addElement("author");
//向author元素中添加firstname,lastname元素,并用setText()设置他们的文本
Element firstNameElement=authorElement.addElement("firstname");
firstNameElement.setText("Marcello");
Element lastNameElement=authorElement.addElement("lastname");
lastNameElement.setText("Vitaletti");
return document;
//使用addDocType() 方法添加文档类型说明
//document.addDocType("catalog",null,"file://c:/Dtds/catalog.dtd");
/**try {
XMLWriter output = new XMLWriter(
new FileWriter( new File("mycatalog.xml") ));
output.write( document );
output.close();
}
catch(IOException e)
{System.out.println(e.getMessage());}**/
}
/**
* 格式化XML文档,并按指定字符集输出
* @param document
* @param fileName
* @param encoding 编码格式
* @return 返回操作结果, 0表失败, 1表成功
*/
public static int saveXml(Document document, String fileName, String encoding) throws UnsupportedEncodingException, FileNotFoundException, IOException{
int returnValue = 0;
XMLWriter output = null;
/** 格式化输出,类型IE浏览一样*/
OutputFormat format = OutputFormat.createPrettyPrint();
/** 指定XML字符集编码*/
format.setEncoding(encoding);
output = new XMLWriter(new FileOutputStream(new File(fileName)), format);
output.write(document);
output.close();
/** 执行成功,需返回1 */
returnValue = 1;
return returnValue;
}
/**
* 修改XML文档,并按指定字符集输出
* @param inputXml
* @param modified_filename 修改后的文件名(含绝对路径)
* @return 返回操作结果, 0表失败, 1表成功
*/
public int modifyDocument(File inputXml,String modified_filename){
int returnValue = 0;
try{
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(inputXml);
//根据XPath语法查询结点catalog下的journal下的article的level属性
List list = document.selectNodes("/catalog/journal/article/@level" );
Iterator iter=list.iterator();
while(iter.hasNext()){
Attribute attribute=(Attribute)iter.next();
if(attribute.getValue().equals("Intermediate")) //如果属性值是Intermediate
attribute.setValue("Introductory");
}
list = document.selectNodes("//article/@date" );
iter=list.iterator();
while(iter.hasNext()){
Attribute attribute=(Attribute)iter.next();
if(attribute.getValue().equals("December-2001"))
attribute.setValue("October-2002");
}
list = document.selectNodes("//article" );
iter=list.iterator();
while(iter.hasNext()){
Element element=(Element)iter.next();
Iterator iterator=element.elementIterator("title");
while(iterator.hasNext()){
Element titleElement=(Element)iterator.next();
if(titleElement.getText().equals("Java configuration with XML Schema"))
titleElement.setText("Create flexible and extensible XML schema"); }
}
list = document.selectNodes("//article/author" );
iter=list.iterator();
while(iter.hasNext()){
Element element=(Element)iter.next();
Iterator iterator=element.elementIterator("firstname");
while(iterator.hasNext()){
Element firstNameElement=(Element)iterator.next();
if(firstNameElement.getText().equals("Marcello"))
firstNameElement.setText("Ayesha");
}
}
list = document.selectNodes("//article/author" );
iter=list.iterator();
while(iter.hasNext()){
Element element=(Element)iter.next();
Iterator iterator=element.elementIterator("lastname");
while(iterator.hasNext()){
Element lastNameElement=(Element)iterator.next();
if(lastNameElement.getText().equals("Vitaletti"))
lastNameElement.setText("Malik");
}
}
XMLWriter output = new XMLWriter(
new FileWriter( new File(modified_filename) ));
output.write( document );
output.close();
}
catch(DocumentException e)
{
System.out.println(e.getMessage());
}
catch(IOException e){
System.out.println(e.getMessage());
}
/** 执行成功,需返回1 */
returnValue = 1;
return returnValue;
}
public static void main(String[] argv) {
Rt savedomtoxml=new Rt();
Document doc=savedomtoxml.generateDocument();
try{
int re=savedomtoxml.saveXml(doc,"savexml.xml","gb2312"); //生成的xml文件默认状态和类文件在同一个目录下
System.out.println(re);
}
catch(IOException e)
{System.out.println(e.getMessage());}
try{
int modifyre=savedomtoxml.modifyDocument(new File("H:/dom4j/rt/orginal.xml"));
System.out.println(modifyre);
}
catch(Exception e)
{System.out.println(e.getMessage());}
}
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/47207/showart_458878.html |
|