先来一段网上的废话:
om4j是一个Java的XML API,类似于jdom,用来读写XML文件的。dom4j是一个非常非常优秀的Java
XML API,具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件,可以在
SourceForge上找到它。在IBM developerWorks上面可以找到一篇文章,对主流的Java XML API进行的
性能、功能和易用性的评测,dom4j无论在那个方面都是非常出色的。如今你可以看到越来越多的Java软件都在
使用dom4j来读写XML,特别值得一提的是连Sun的JAXM也在用dom4j。这是必须使用的jar包,Hibernate
用它来读写配置文件。
注意,如果要使用Dom4j创建xml文档,只需要导入dom4j的jar包即可,如果要用dom4j解析xml文档,且使用xpath来解析,则需要导入jaxen-xx.xx.jar包,否则会报错。
下面来创建一个xml文档:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <books> <!--这是添加的注释--> <firstbook name="飞翔的小鸟" price="12¥"> <theauthor> <authorname>Stfen.Cofffe Orce</authorname> <otherbooks><![CDATA[《中国行》,《红花郎》,《哦哦地》...]]></otherbooks> </theauthor> </firstbook> <secondbook name="蚂蚁上树" price="23¥"> <theauthor> <authorname>Wen Jim.Sam</authorname> <otherbooks><![CDATA[《哦看看》,《亚西门》....]]></otherbooks> </theauthor> </secondbook> </books>
1.创建xml文档
package com.wang.test;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Attribute;
import org.dom4j.io.OutputFormat;
import java.io.FileOutputStream;
import org.dom4j.io.XMLWriter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class CreateXML {
//创建log4j对象
private static Log log = LogFactory.getLog(CreateXML.class);
public static void main(String[] args){
//创建xml文档对象
Document document = DocumentHelper.createDocument();
// 设置文档DocType,这里为了举例,添加hibernate的DocType
document.addDocType("hibernate-configuration",
"-//Hibernate/Hibernate Configuration DTD 3.0//EN",
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd");
//创建文档的根节点books,文档的根节点只能有一个,多加会出错
Element root = document.addElement("books");
//添加一行注释
root.addComment("这是添加的注释");
//创建根节点的一级子节点firstbook
Element bookOne = root.addElement("firstbook");
//为节点firstbook添加属性
bookOne.addAttribute("name", "飞翔的小鸟");
bookOne.addAttribute("price", "12¥");
//为节点firstbook添加子节点theauthor
Element authorOne = bookOne.addElement("theauthor");
//为节点theauthor添加子节点authorname
Element nameOne = authorOne.addElement("authorname");
//为authornamer节点添加文本节点
nameOne.setText("Stfen.Cofffe Orce");
//为节点theauthor添加子节点otherbooks
Element booksOne = authorOne.addElement("otherbooks");
//为节点othersbooks添加CDATA数据
booksOne.addCDATA("《中国行》,《红花郎》,《哦哦地》...");
/**
* 第二种方法增加节点,内容,属性等。先创建节点,属性,然后使用add加入。
*/
//创建节点secondbook
Element bookTwo = DocumentHelper.createElement("secondbook");
//创建属性对象bookname,createAttribute的第一个参数表示该属性的拥有这者,可以写,也可为null
Attribute bookname = DocumentHelper.createAttribute(bookTwo, "name", "蚂蚁上树");
//创建属性对象bookPrice
Attribute bookPrice = DocumentHelper.createAttribute(bookTwo, "price", "23¥");
//将创建的属性添加到节点对象当中
bookTwo.add(bookname);
bookTwo.add(bookPrice);
//创建节点author
Element author = DocumentHelper.createElement("theauthor");
Element authorName = DocumentHelper.createElement("authorname");
authorName.setText("Wen Jim.Sam");
Element otherbooks = DocumentHelper.createElement("otherbooks");
otherbooks.addCDATA("《哦看看》,《亚西门》....");
//将创建的节点authorName,otherbooks添加到author下
author.add(authorName);
author.add(otherbooks);
//将创建的节点author添加到节点bookTwo下
bookTwo.add(author);
//将创建的节点bookTwo添加到根节点root下,成为其一级节点
root.add(bookTwo);
// 最后将生成的文档保存到文件当中
//创建格式化类
OutputFormat format = OutputFormat.createPrettyPrint();
//设置编码格式
format.setEncoding("UTF-8");
// 创建输出流,如果此处使用Writer的类,则需要指定输入的编码格式,
// 而使用OutputStream则不用指定编码格式
FileOutputStream output = null;
try{
output = new FileOutputStream("D:\\books.xml");
// 创建XML输出流
XMLWriter writer = new XMLWriter(output,format);
writer.write(document);
writer.close();
output.close();
log.debug("xml创建完成");
}catch(Exception e){
log.error(e);
}
}
}
2.修改xml文档。要修改,必须要找到修改的地方,也就是先解析xml文档,再修改目标。在解析xml文档时,有人会用传统的方式,也有人会用Xpath的方式,推荐使用xpath.下面贴个xpath的路径表,以供差用。
算了,发个xpath的教程地址吧:http://www.w3school.com.cn/xpath/xpath_syntax.asp
修改xml文档:
public class ChangXml {
private static Log log = LogFactory.getLog(ChangXml.class);
public static void main(String[] args){
// org.dom4j.io提供了两个类:SAXReader和DOMReader.
// DOMReader只能一个现有的w3c DOM树构建 dom4j树,即只能从一个org.w3c.dom.Document 中构建org.dom4j.Document树;
// 而SAXReader则使用 SAX解析器,从不同的输入源构建dom4j树,如可以从xml文件中读取并构建dom4j树。
1:使用DOMReader解析
// DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// DocumentBuilder db = dbf.newDocumentBuilder();
// File file = new File("d:/skills.xml");
// org.w3c.dom.Document domDocument = db.parse(file);
// DOMReader reader = new DOMReader();
// org.dom4j.Document document = reader.read(domDocument);
// 2:使用SAXReader解析
SAXReader reader = new SAXReader();
Document document = null;
try{
document = reader.read(new File("d:/books.xml"));
}catch(Exception e){
log.error(e);
}
// 将所有的authorname元素的文本修改为"wangyinan"
//根据xpath获得所有的authorname元素的文本值
//使用dom4j时调用XPath解析时, 要在项目中加入jaxen-xx.xx.jar
List authorNameList = document.selectNodes("//authorname");
for(Iterator iter = authorNameList.iterator();iter.hasNext();){
Element node = (Element)iter.next();
log.debug(node.getText());
//将属性值改为“wangyinan”
node.setText("wangyinan");
}
// 将所有的price属性值修改50美元
List priceList = document.selectNodes("//@price");
for(Iterator iter = priceList.iterator();iter.hasNext();){
Attribute attribute = (Attribute)iter.next();
log.debug("old value="+attribute.getValue());
attribute.setValue("50美元");
}
// 删除firstbook/theauthor元素下的otherbooks元素
// 由document文档对象不能直接删除节点
// Element elementOhterbooks =(Element)document.selectSingleNode("/books/firstbook//otherbooks");
// log.debug(elementOhterbooks.getText());
// document.remove(elementOhterbooks);
// 元素不能删除其非直接子元素
Element root = document.getRootElement();
// Element firstbook = (Element)document.selectSingleNode("/books/firstbook");
// Element otherbooks = (Element)document.selectSingleNode("/books/firstbook//otherbooks");
// log.debug(otherbooks.getText());
// firstbook.remove(otherbooks);
Element theauthor =(Element)document.selectSingleNode("/books/firstbook//theauthor");
Element otherbooks = theauthor.element("otherbooks");
log.debug(otherbooks.getText());
theauthor.remove(otherbooks);
// 修改后,要把修改的Document保存进文件内,不保存的话,修改成功不了
// 创建格式化类
OutputFormat format = OutputFormat.createPrettyPrint();
// 设置编码格式
format.setEncoding("UTF-8");
// 创建输出流,如果此处使用Writer的类,则需要指定输入的编码格式,
// 而使用OutputStream则不用指定编码格式
FileOutputStream output = null;
try{
output = new FileOutputStream("D:\\books.xml");
// 创建XML输出流
XMLWriter writer = new XMLWriter(output,format);
writer.write(document);
writer.close();
output.close();
log.debug("chang success");
}catch(Exception e){
log.error(e);
}
}
}