(一)移除节点及属性

    /**移除节点和属性的操作
     * @throws DocumentException
     */
    public void RemoveOperator() throws DocumentException{
        //待生成xml的字符串
        String str="<root><book type='science'><Name>Java</Name><price>100</price></book>"
            +"<book type='society'><Name>Society security</Name><price>130</price></book>"
            +"<author><name>chb</name><sex>boy</sex></author></root>";
        //生成一个Document
        Document document = DocumentHelper.parseText(str);
        
        Element root=document.getRootElement();
        //删除类型为society的book节点
        Element book_society=(Element)document.selectSingleNode("//book[@type='society']");
        root.remove(book_society);
        System.out.println("1。正确的删除了类型为society的book节点");
        System.out.println(document.asXML());
        
        //删除sex节点
        Element sex=(Element)root.selectSingleNode("//sex");
        
        //从root节点删除
        root.remove(sex);
        System.out.println("2。这样是不能删除sex节点的");
        System.out.println(document.asXML());
        
        //从author节点删除
        root.element("author").remove(sex);
        System.out.println("3。这样就可以正确删除sex节点");
        System.out.println(document.asXML());
        
        //删除属性
        Attribute type=root.element("book").attribute("type");
        root.element("book").remove(type);
        System.out.println("4。正确删除book节点的type属性");
        System.out.println(document.asXML());
    }

输出结果为:

1。正确的删除了类型为society的book节点
<?xml version="1.0" encoding="UTF-8"?>
<root><book type="science"><Name>Java</Name><price>100</price></book><author><name>chb</name><sex>boy</sex></author></root>
2。这样是不能删除sex节点的
<?xml version="1.0" encoding="UTF-8"?>
<root><book type="science"><Name>Java</Name><price>100</price></book><author><name>chb</name><sex>boy</sex></author></root>
3。这样就可以正确删除sex节点
<?xml version="1.0" encoding="UTF-8"?>
<root><book type="science"><Name>Java</Name><price>100</price></book><author><name>chb</name></author></root>
4。正确删除book节点的type属性
<?xml version="1.0" encoding="UTF-8"?>
<root><book><Name>Java</Name><price>100</price></book><author><name>chb</name></author></root>

分析:

第二个输出结果不能删除sex节点,我们需要看dom4j的API

remove

public boolean remove(Element element)
Removes the given Element if the node is an immediate child of this branch. If the given node is not an immediate child of this branch then theNode.detach()method should be used instead.

Parameters:
element - is the element to be removed
Returns:
true if the element was removed

从中我们可以看出,remove只能用在它自己的直接孩子节点上,不能用在孙子节点上,因为sex节点不是root节点的直接孩子节点,所以不能删除;而sex节点却是author节点的直接孩子节点,所以第三个输出可以删除。

(二)将两个Document合并为一个Document

先看一个错误的情况

(1)使用add()方法添加

public void CombineDocument() throws DocumentException{
        //待生成两个Document的字符串
        String str_book="<root><book type='science'><Name>Java</Name><price>100</price></book>"
            +"<book type='society'><Name>Society security</Name><price>130</price></book>"
            +"</root>";
        String str_author="<root><author><name>chb</name><sex>boy</sex></author></root>";
        
        //生成两个Document
        Document doc_book=DocumentHelper.parseText(str_book);
        Document doc_author=DocumentHelper.parseText(str_author);
        
        //取出doc_author的author节点,添加到doc_book的根结点
        Element author=(Element)doc_author.selectSingleNode("//author");
        doc_book.getRootElement().add(author);
        System.out.println(doc_book.asXML());
    }

调用CombineDocument函数,会出现以下错误:

org.dom4j.IllegalAddException: The node "org.dom4j.tree.DefaultElement@17bd6a1 [Element: <author attributes: []/>]" could not be added to the element "root" because: The Node already has an existing parent of "root"
 at org.dom4j.tree.AbstractElement.addNode(AbstractElement.java:1521)
 at org.dom4j.tree.AbstractElement.add(AbstractElement.java:1002)
 at xml_chb.dom4j_chb.CombineDocument(dom4j_chb.java:189)
 at xml_chb.dom4j_chb.main(dom4j_chb.java:199)
Exception in thread "main"

即提示author节点已经有一个root节点了,不能再添加到另一个节点上去。

(2)使用appendContent()方法

即将doc_book.getRootElement().add(author);

改为:doc_book.getRootElement().appendContent(author);

输出结果为:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<book type="science"><Name>Java</Name><price>100</price></book>
<book type="society"><Name>Society security</Name><price>130</price></book>
<name>chb</name><sex>boy</sex>
</root>

可以看出,缺少了author节点,只是把author节点的子节点添加上去了,但是由此可见,appendContent方法是有希望的。

我们看一下dom4j的API:

appendContent

public void appendContent(Branch branch)
Appends the content of the given branch to this branch instance. This method behaves like the Collection.addAll(java.util.Collection)method.

Parameters:
branch - is the branch whose content will be added to me.

(3)使用正确的appendContent方法

将:Element author=(Element)doc_author.selectSingleNode("//author");

doc_book.getRootElement().appendContent(author);

改为:doc_book.getRootElement().appendContent(doc_author.getRootElement());

输出:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<book type="science"><Name>Java</Name><price>100</price></book>
<book type="society"><Name>Society security</Name><price>130</price></book>
<author><name>chb</name><sex>boy</sex></author>
</root>

是正确结果

(4)另一种可行的方法

public void CombineDocument() throws DocumentException{
        //待生成两个Document的字符串
        String str_book="<root><book type='science'><Name>Java</Name><price>100</price></book>"
            +"<book type='society'><Name>Society security</Name><price>130</price></book>"
            +"</root>";
        String str_author="<root><author><name>chb</name><sex>boy</sex></author></root>";
        
        //生成两个Document
        Document doc_book=DocumentHelper.parseText(str_book);
        Document doc_author=DocumentHelper.parseText(str_author);
        
        //新生成一个Document
        Element author=DocumentHelper.createElement("author");
        author.appendContent((Element)doc_author.selectSingleNode("//author"));
        //当前author尚无父节点,所以可以使用add方法添加
        doc_book.getRootElement().add(author);

        System.out.println(doc_book.asXML());
    }
 
 

documeant 学习总结(二)的更多相关文章

  1. crawler4j 学习(二)

    crawler4j 学习(二) 实现控制器类以制定抓取的种子(seed).中间数据存储的文件夹.并发线程的数目: public class Controller { public static voi ...

  2. 从零开始学习jQuery (二) 万能的选择器

    本系列文章导航 从零开始学习jQuery (二) 万能的选择器 一.摘要 本章讲解jQuery最重要的选择器部分的知识. 有了jQuery的选择器我们几乎可以获取页面上任意的一个或一组对象, 可以明显 ...

  3. Android Animation学习(二) ApiDemos解析:基本Animators使用

    Android Animation学习(二) ApiDemos解析:基本Animatiors使用 Animator类提供了创建动画的基本结构,但是一般使用的是它的子类: ValueAnimator.O ...

  4. AspectJ基础学习之二搭建环境(转载)

    AspectJ基础学习之二搭建环境(转载) 一.下载Aspectj以及AJDT 上一章已经列出了他的官方网站,自己上去download吧.AJDT是一个eclipse插件,开发aspectj必装,他可 ...

  5. WPF的Binding学习笔记(二)

    原文: http://www.cnblogs.com/pasoraku/archive/2012/10/25/2738428.htmlWPF的Binding学习笔记(二) 上次学了点点Binding的 ...

  6. AJax 学习笔记二(onreadystatechange的作用)

    AJax 学习笔记二(onreadystatechange的作用) 当发送一个请求后,客户端无法确定什么时候会完成这个请求,所以需要用事件机制来捕获请求的状态XMLHttpRequest对象提供了on ...

  7. MyBatis学习系列二——增删改查

    目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring 数据库的经典操作:增删改查. 在这一章我们主要说明一下简单的查询和增删改, ...

  8. MyBatis学习 之 二、SQL语句映射文件(2)增删改查、参数、缓存

    目录(?)[-] 二SQL语句映射文件2增删改查参数缓存 select insert updatedelete sql parameters 基本类型参数 Java实体类型参数 Map参数 多参数的实 ...

  9. MyBatis学习 之 二、SQL语句映射文件(1)resultMap

    目录(?)[-] 二SQL语句映射文件1resultMap resultMap idresult constructor association联合 使用select实现联合 使用resultMap实 ...

  10. UML学习(二)-----类图

    UML学习(二)-----类图 http://www.cnblogs.com/silent2012/archive/2011/09/07/2169946.html http://www.cnblogs ...

随机推荐

  1. java web 读取配置文件两种方法

    package com.tsinghua.getDataBaseConn; import java.io.IOException;import java.io.InputStream;import j ...

  2. Hadoop Yarn Capacity Scheduler

    Capacity 调度器配置 <property> <name>yarn.resourcemanager.scheduler.class<name> <val ...

  3. linux下使用gtest框架进行c/c++单元测试

    linux下使用gtest框架进行c/c++单元测试 前言 关于此次开发工具的选择,因为我最近尝试在linux下使用vim进行c/c++编程,且之前已经对vim进行了相关的配置,所以这里应作业要求直接 ...

  4. 浅析 python中的 print 和 input 的底层区别!!!

    近期的项目中 涉及到相关知识 就来总结一下 ! 先看源码: def print(self, *args, sep=' ', end='\n', file=None): # known special ...

  5. 【HDU5862】Counting Intersections

    题意 有n条线段,且都平行于坐标轴.对于每条线段,给出两个端点的坐标.问一共有多少个线段的交点. 分析 最最简单的扫描法了.用线段树或者树状数组都可以. 由题目可知,线段只有两种,要么平行于x轴要么平 ...

  6. 刷题向》一道关于位运算的神题(BZOJ3668)(HARD-)

    个人觉得这道题对于位运算的加深理解很有意义 根据题目所说,我们要求出一个在给定范围里的自变量,使得最终结果最大. 那么因为这道题是针对于位运算的,所以可以想到用对于位运算取极限情况,即对于“0”和“( ...

  7. iOS8 无缝切换WKWebView,借鉴IMYWebview,解决进度条,cookie,本地页面等问题

    webkit使用WKWebView来代替IOS的UIWebView和OSX的WebView,并且使用Nitro JavaScript引擎,这意味着所有第三方浏览器运行JavaScript将会跟safa ...

  8. DALSA相机SDK不完全教程

    1.SDK介绍 Dalsa是全球顶尖的CCD/CMOS芯片和相机制造商,总部位于加拿大,我使用的是 Dalsa的 Genie_TS_M1920(黑白)和 Genie_TS_C2048(彩色)两款工业相 ...

  9. SQL虚拟数字辅助表

    虚拟数字辅助表是一个整数序列,可以用来完成多种不同的任务,如生成日期跟时间值序列,及分裂值列表.要用查询逻辑产生一个大的整数序列,可以使用交叉连接(cross join). 交叉联接(cross jo ...

  10. vSphere5.5体系结构

    1.vSphere5.5体系结构 vSphere5.5作为云集算操作系统,可以虚拟化服务器.存储.网络在内的整个IT基础架构,将这些架构转化为易于管理的虚拟化!vSphere5.5从逻辑上,可以划分为 ...