一、简介

1.网上下载DOM4J 1.6.1压缩包,解压开之后,发现几个目录和一个jar文件,jar文件是必须的文件其它目录:

docs目录:帮助文档的目录,单击index.html:

Quick start是快速入门超链接,主要参考这里的代码完成对dom4j的认识,并完成CRUD的操作。

Javdoc(1.6.1)是dom4j的帮助文档,需要查找相关信息的时候主要参考这里。

lib目录:该目录下有相关若干jar包,他们是dom4j-1.6.1.jar的依赖文件,当使用XPath解析XML文档提示错误信息的时候,应当将该文件夹下面的相关jar文件加入路径。

src目录:该目录存放源文件,可以压缩该目录以便于查找源代码。

2.使用dom4j的好处。

最大的好处就是能够大大简化对XML文档的操作。

但应当注意,导包的时候应当导入的包是dom4j的包,而不是原来的包了,比如:Document对象应当导入的包名为:org.dom4j.Document。

3.准备工作:对项目名称右键单击,新建目录lib,对着该目录右键单击,新建目录dom4j,将相关的jar文件复制到该目录中,选中所有的jar文件,右键build path->addtobuildpath,效果图:

另外Books类

 package p00.domain;

 public class Book {
public String title;
public double price;
public String id;
public String getId()
{
return id;
}
public void setId(String id)
{
this.id=id;
}
public String getTitle()
{
return title;
}
public double getPrice()
{
return price;
}
public void setTitle(String title)
{
this.title=title;
}
public void setPrice(double price)
{
this.price=price;
}
public String toString()
{
return "图书ISBN为:"+id+" 书名为:"+title+" 价格为:"+price;
} }

books.xml文档:

 <?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="book1">
<title>JAVA编程思想</title>
<price>80.00</price>
</book>
<book id="book2">
<title>JAVA核心技术</title>
<price>100.00</price>
</book>
</books>

持久化保存到xml文档的方法。

使用第一种方法:

 private static void writeToNewXMLDocument(Document document) throws Exception {
FileWriter fw=new FileWriter("xmldata/newbooks.xml");
OutputFormat of=OutputFormat.createPrettyPrint();
of.setEncoding("gbk");//如果改为utf-8则出现乱码。
XMLWriter writer=new XMLWriter(fw,of);
writer.write(document);
writer.close();//注意不要忘记关流。
}

使用该方法出现了中文乱码问题,原因是文件编码为gbk,二文件内容编码为utf-8,产生原因不明。因此改用另外一种方法,该方法使用OutputStreamWriter类实现特定编码方式的写入,解决了中文乱码问题

   /**
* 通过document对象将内存中的dom树保存到新的xml文档,使用特定的编码方式:utf-8。
* @param document
* @throws Exception
*/
private static void writeToNewXMLDocument(Document document) throws Exception {
FileOutputStream fos=new FileOutputStream(new File("xmldata/newbooks.xml"));
OutputStreamWriter osw=new OutputStreamWriter(fos,"utf-8");
/**
*使用这种写法才不会产生乱码
*/
XMLWriter writer=new XMLWriter(osw);
writer.write(document);
writer.close();
}

二、CRUD操作。

1、读取(R)

 private static List<Book> readAllElementsFromXMLDocument(Document document) {
List<Book>books=new ArrayList<Book>();
Element root=document.getRootElement();
List list=root.elements();
for(int i=0;i<list.size();i++)
{
Element book=(Element) list.get(i);
Book b=new Book();
String id=book.attributeValue("id");
List ll=book.elements();
b.setId(id);
System.out.println(id);
for(int j=0;j<ll.size();j++)
{
Element element=(Element) ll.get(j);
if("title".equals(element.getName()))
{
String title=element.getText();
b.setTitle(title);
System.out.println(title);
}
if("price".equals(element.getName()))
{
String price=element.getText();
double p=Double.parseDouble(price);
b.setPrice(p);
System.out.println(price);
}
}
books.add(b);
}
return books;
}

效果图:

2、修改(U)

     /**
* 该方法的作用是修改document中的内容
* 将id为b002的元素的title改为Java Core,Price改为100.01
* @param document
*/
private static void ModifyInformationOfXMLDocument(Document document) {
Element root=document.getRootElement();
List books=root.elements();
for(int i=0;i<books.size();i++)
{ Element book=(Element) books.get(i);
if("book2".equals(book.attributeValue("id")))
{
for(Iterator it=book.elementIterator();it.hasNext();)
{
Element node=(Element) it.next();
String type=node.getName();
if("title".equals(type))
{
node.setText("JAVA Core");
}
if("price".equals(type))
{
node.setText("100.01");
}
}
}
}
}

效果图:

<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="book1">
<title>JAVA编程思想</title>
<price>80.00</price>
</book>
<book id="book2">
<title>JAVA Core</title>
<price>100.01</price>
</book>
</books>

3、删除(D)

 /**
* 该方法实现了使用dom4j的删除元素的功能
* @param document
*/
private static void deleteInformationOfXMLDocument(Document document) {
Element root=document.getRootElement();
for(Iterator it=root.elementIterator();it.hasNext();)
{
Element book=(Element) it.next();
String id=book.attributeValue("id");
if("book1".equals(id))
{
Element parent=book.getParent();
parent.remove(book);
}
}
}

效果图:

<?xml version="1.0" encoding="UTF-8"?>
<books> <book id="book2">
<title>JAVA核心技术</title>
<price>100.00</price>
</book>
</books>

4、添加(C)

  /**
* 实现了添加新节点:book的功能
* @param document
*/
private static void addNewBookToXMLDocument(Document document) {
Element root=document.getRootElement();
Element newBook=root.addElement("book");
newBook.addAttribute("id", "book3");
Element title=newBook.addElement("title");
title.setText("凤姐玉照");
Element price=newBook.addElement("price");
price.setText("10000.01");
}

效果图:

<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="book1">
<title>JAVA编程思想</title>
<price>80.00</price>
</book>
<book id="book2">
<title>JAVA核心技术</title>
<price>100.00</price>
</book>
<book id="book3"><title>凤姐玉照</title><price>10000.01</price></book></books>

5.完整代码

 package p03.CRUDToXMLDocumentByDom4j;

 import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter; import p00.domain.Book; /**
* 该类通过dom4j技术实现了对xml文档的增删改查。
* @author kdyzm
*
*/
public class SetAllElementsByDom4j {
public static void main(String args[]) throws Exception
{
/**
* 第一步,得到document对象。
*/
Document document=getDocument(); /**
* 第二步,修改得到的document对象
*/ /**
* 首先,读取功能
*/
// List<Book>books=readAllElementsFromXMLDocument(document);
// traverseBooks(books); /**
* 其次,修改功能
* 修改内容:将id为b002的元素的title改为Java Core,Price改为100.01
*/
// ModifyInformationOfXMLDocument(document); /**
* 再者:实现删除功能
* 删除内容:删除掉id为book1的元素内容。
*/
// deleteInformationOfXMLDocument(document); /**
* 最后:实现添加i新元素功能
* 添加内容:id为book3,title内容为:凤姐玉照,price内容为10000.00
*/
// addNewBookToXMLDocument(document); /**
* 第三步:将得到的document对象持久化保存到硬盘(XML)
*/
writeToNewXMLDocument(document);
}
/**
* 实现了添加新节点:book的功能
* @param document
*/
private static void addNewBookToXMLDocument(Document document) {
Element root=document.getRootElement();
Element newBook=root.addElement("book");
newBook.addAttribute("id", "book3");
Element title=newBook.addElement("title");
title.setText("凤姐玉照");
Element price=newBook.addElement("price");
price.setText("10000.01");
} /**
* 该方法实现了使用dom4j的删除元素的功能
* @param document
*/
private static void deleteInformationOfXMLDocument(Document document) {
Element root=document.getRootElement();
for(Iterator it=root.elementIterator();it.hasNext();)
{
Element book=(Element) it.next();
String id=book.attributeValue("id");
if("book1".equals(id))
{
Element parent=book.getParent();
parent.remove(book);
}
}
} /**
* 该方法的作用是修改document中的内容
* 将id为b002的元素的title改为Java Core,Price改为100.01
* @param document
*/
private static void ModifyInformationOfXMLDocument(Document document) {
Element root=document.getRootElement();
List books=root.elements();
for(int i=0;i<books.size();i++)
{ Element book=(Element) books.get(i);
if("book2".equals(book.attributeValue("id")))
{
for(Iterator it=book.elementIterator();it.hasNext();)
{
Element node=(Element) it.next();
String type=node.getName();
if("title".equals(type))
{
node.setText("JAVA Core");
}
if("price".equals(type))
{
node.setText("100.01");
}
}
}
}
}
/**
* 遍历集合
* @param books
*/
private static void traverseBooks(List<Book> books) {
for(Iterator<Book>iterator=books.iterator();iterator.hasNext();)
{
Book book=iterator.next();
System.out.println(book);
}
}
/**
* 该方法实现了对xml文档的读取功能
* @param document
* @return
*/
private static List<Book> readAllElementsFromXMLDocument(Document document) {
List<Book>books=new ArrayList<Book>();
Element root=document.getRootElement();
List list=root.elements();
for(int i=0;i<list.size();i++)
{
Element book=(Element) list.get(i);
Book b=new Book();
String id=book.attributeValue("id");
List ll=book.elements();
b.setId(id);
System.out.println(id);
for(int j=0;j<ll.size();j++)
{
Element element=(Element) ll.get(j);
if("title".equals(element.getName()))
{
String title=element.getText();
b.setTitle(title);
System.out.println(title);
}
if("price".equals(element.getName()))
{
String price=element.getText();
double p=Double.parseDouble(price);
b.setPrice(p);
System.out.println(price);
}
}
books.add(b);
}
return books;
}
/**
* 通过document对象将内存中的dom树保存到新的xml文档,使用特定的编码方式:utf-8。
* @param document
* @throws Exception
*/
private static void writeToNewXMLDocument(Document document) throws Exception {
FileOutputStream fos=new FileOutputStream(new File("xmldata/newbooks.xml"));
OutputStreamWriter osw=new OutputStreamWriter(fos,"utf-8");
/**
*使用这种写法才不会产生乱码
*/
XMLWriter writer=new XMLWriter(osw);
writer.write(document);
writer.close();
} /**
* 该方法用于得到document对象。
* @return
* @throws Exception
*/
private static Document getDocument() throws Exception {
SAXReader sr=new SAXReader();
Document document=sr.read("xmldata/books.xml");
return document;
}
}

三、总结

使用dom4j大大减少了代码量,提供了编码效率,推荐使用该方法对XML文档进行解析。

四、使用XPath精确查找制定元素,优化dom4j的解析过程,减少代码量。

【JAVA与DOM4J实现对XML文档的CRUD操作】的更多相关文章

  1. jaxp实现对xml文档的增,删,改,查操作(附源码)浅析

    jaxp,属于javase中的一部分.是对xml进行解析的一个工具类: 既然说到这里,还是讲全一点,讲讲上面说到的xml的解析技术. xml的一个标记型文档. 在html的层级结构中,它会在内存中分配 ...

  2. XMLHelper类 源码(XML文档帮助类,静态方法,实现对XML文档的创建,及节点和属性的增、删、改、查)

    以下是代码: using System; using System.Collections.Generic; using System.Linq; using System.Web; using Sy ...

  3. 编写Java程序,使用 dom4j 创建一个 XML 文档,文档名为“city.xml”。注意该文档的格式和数据

    查看本章节 查看作业目录 需求说明: 使用 dom4j 创建一个 XML 文档,文档名为"city.xml".该文档的格式和数据如图所示 实现思路: 创建Java项目,添加dom4 ...

  4. 编写Java程序,现要求使用 dom4j 解析 city.xml 文档,实现省份及对应城市的联动特效,效果如图所示

    查看本章节 查看作业目录 需求说明: 现要求使用 dom4j 解析 city.xml 文档,实现省份及对应城市的联动特效,效果如图所示 实现思路: 创建解析 XML 文档类 ParseXML 和窗体类 ...

  5. 使用DOM进行xml文档的crud(增删改查)操作<操作详解>

    很多朋友对DOM有感冒,这里我花了一些时间写了一个小小的教程,这个能看懂,会操作了,我相信基于DOM的其它API(如JDOM,DOM4J等)一般不会有什么问题. 后附java代码,也可以下载(可点击这 ...

  6. 使用dom4j技术对xml文档进行增删改练习(一)

    整个流程如下面代码所以,并对一些重要代码意义做出详细解释: import java.io.File; import java.io.FileOutputStream; import org.dom4j ...

  7. javaweb学习总结十三(dom4j方式对XML文档进行解析以及Xpath的使用)

    一:dom4j方式介绍 对于xml的解析总共有三种 1:jaxp方式,是sun公司开发的,分为sax方式和dom方式 2:jdom方式,后来其中部分人员参与开发dom4j 3:dom4j方式,是现在企 ...

  8. 2.Java实现基于SOAP的XML文档网络传输及远程过程调用(RPC)-

    转自:https://blog.csdn.net/a214919447/article/details/55260411 SOAP(Simple Object Access Protocol,简单对象 ...

  9. 编写Java程序,创建一个 XML 文档,文档名为“hero.xml”,用于保存“王者荣耀”的英雄信息。

    查看本章节 查看作业目录 需求说明: 创建一个 XML 文档,文档名为"hero.xml",用于保存"王者荣耀"的英雄信息.英雄信息包括编号(id).姓名(na ...

随机推荐

  1. STS新建的maven项目报错问题

    STS新建的maven项目报错问题 解决方法:打开pom.xml文件添加 <dependency> <groupId>javax.servlet</groupId> ...

  2. ndk学习16: unix domain socket

    一.UNIX Domain Socket 概念: UNIX Domain Socket是在socket架构上发展起来的用于同一台主机的进程间通讯(IPC) 特点: 1. 它不需要经过网络协议栈,不需要 ...

  3. DevStack安装时报“download of get-pip.py failed”

    ref from : http://www.voidcn.com/blog/ldli8979/article/p-5005958.html 这个可能会有多种原因造成.网上搜了一下,有人说需要手动下载, ...

  4. 基于Hadoop 2.6.0运行数字排序的计算

    上个博客写了Hadoop2.6.0的环境部署,下面写一个简单的基于数字排序的小程序,真正实现分布式的计算,原理就是对多个文件中的数字进行排序,每个文件中每个数字占一行,排序原理是按行读取后分块进行排序 ...

  5. 解决 vs2010 联接sql 2005 时 报错未能加载文件或程序集“Microsoft.SqlServer.Management.Sdk.Sfc

    http://blogs.msdn.com/b/sqlnativeclient/archive/2008/05/30/sqlncli-msi-for-sql-server-2008.aspx 关键是这 ...

  6. gtk+-3.21.4 static build step in windows XP

    In recent days the weather is very hot Unable to sleep properly Under the state of daze research gtk ...

  7. [第三方]SDWebImage获取网络图片控件的用法

    #import "UIImageView+WebCache.h" @interface WeatherViewController ()<UISearchBarDelegat ...

  8. codeforces 493B.Vasya and Wrestling 解题报告

    题目链接:http://codeforces.com/problemset/problem/493/B 题目意思:给出 n 个 techniques,每个 technique 的值为 ai. ai & ...

  9. C#字符串的四舍五入

    Round(Decimal) Round(Double) Round(Decimal, Int32) Round(Decimal, MidpointRounding) Round(Double, In ...

  10. JS里设定延时:js中SetInterval与setTimeout用法

     js中SetInterval与setTimeout用法 JS里设定延时: 使用SetInterval和设定延时函数setTimeout 很类似.setTimeout 运用在延迟一段时间,再进行某项操 ...