`

Dom4j使用

 
阅读更多

先来一段网上的废话:

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);
			}
		   
	}
}

 

 

分享到:
评论

相关推荐

    dom4j使用手册

    dom4j使用手册;

    DOM4J使用详解

    DOM4J使用详解包括具体的增加、删除、获取节点、属性

    dom4j使用教程

    dom4j使用教程 感觉很好 与大家共享

    XSD使用dom4j校验XML

    XSD使用dom4j校验XML

    Dom4j使用简介

    Dom4j使用简介,日志 开发java必看,初级高级开发必看

    DOM4J jar包 xml解析 所有的dom4j-1.6.1 dom4j-2.0.2 dom4j-2.1.1包 导入直接使用

    DOM4J jar包 所有的包 xml解析 dom4j-1.6.1 dom4j-2.0.2 dom4j-2.1.1 导入直接使用

    Dom4j 使用指南.rar

    Dom4j 使用指南 对学习xml的用户有很大的帮助

    Dom4J使用手册和说明

    Dom4J使用手册和说明 ,方便有需要的人参考和使用。 Web开发,Java开发。。。。

    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 ...DOM4J使用起来非常简单。

    dom4j使用教程+dom4j.jar

    收集于网络的dom4j解析使用,包括创建,修改,删除等并且有jar文件一同上传

    Dom4j的使用(全而好的文章)

    Dom4j的使用(全而好的文章),不看后悔哦。刚学习过,灰常好的资源。

    dom4j dom4j dom4j dom4j

    dom4j dom4j dom4j dom4j dom4j dom4j

    dom4j使用简介

    Dom4j 是一个易用的、开源的库,用于 XML,XPath 和 XSLT。它应用于 Java 平 台,采用了 Java 集合框架并完全支持 DOM,SAX 和 JAXP

    DOM4J的jar包和API

    与JDOM不同的是,dom4j使用接口和抽象基类,虽然Dom4j的API相对要复杂一些,但它提供了比JDOM更好的灵活性。 Dom4j是一个非常优秀的Java XML API,具有性能优异、功能强大和极易使用的特点。现在很多软件采用的Dom4...

    Dom4j 使用简介

    Dom4j 使用简介,Dom4j 使用简介

    dom4j的使用教程

     DOM4J使用起来非常简单。只要你了解基本的XML-DOM模型,就能使用。然而他自己带的指南只有短短一页(html),不过说的到挺全。国内的中文资料很少。因而俺写这个短小的教程方便大家使用,这篇文章仅谈及基本的用法...

    dom4j使用介绍

    里面有dom4j的相关资料,还有一些dom4j的相关接口、属性和方法,需要的拿去看看吧

    dom4j-2.1.1-API文档-中英对照版.zip

    赠送jar包:dom4j-2.1.1.jar; 赠送原API文档:dom4j-2.1.1-javadoc.jar; 赠送源代码:dom4j-2.1.1-sources.jar; 赠送Maven依赖信息文件:dom4j-2.1.1.pom; 包含翻译后的API文档:dom4j-2.1.1-javadoc-API文档-...

    dom4j 简单教程

    本人总结的dom4j使用方法,希望能帮助刚刚接触的朋友。

Global site tag (gtag.js) - Google Analytics