Dom4j是一个易于使用的,开源的库,在Java平台上与XML,XPath,XSLT协同工作。使用Java集合框架,全面支持DOM,SAX,JAXP。 
官方网站:http://dom4j.org

1.将XML文件转换为一个Document对象

import java.net.URL;

import org.dom4j.Document; 
import org.dom4j.DocumentException; 
import org.dom4j.io.SAXReader;

public class Foo {

public Document parse(URL url) throws DocumentException { 
        SAXReader reader = new SAXReader(); 
        Document document = reader.read(url); 
        return document; 
    } 
}

2.很多方法用于操作Document,可以返回标准的Java迭代器

public void bar(Document document) throws DocumentException {

Element root = document.getRootElement();

// iterate through child elements of root 
        for ( Iterator i = root.elementIterator(); i.hasNext(); ) { 
            Element element = (Element) i.next(); 
            // do something 
        }

// iterate through child elements of root with element name "foo" 
        for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) { 
            Element foo = (Element) i.next(); 
            // do something 
        }

// iterate through attributes of root 
        for ( Iterator i = root.attributeIterator(); i.hasNext(); ) { 
            Attribute attribute = (Attribute) i.next(); 
            // do something 
        } 
     }

3.快速循环

如果你需要遍历一个很大的XML文档,可以使用快速循环(递归)来改善性能。可以避免为每一次循环都创建一个迭代器对象。

public void treeWalk(Document document) { 
        treeWalk( document.getRootElement() ); 
    }

public void treeWalk(Element element) { 
        for ( int i = 0, size = element.nodeCount(); i < size; i++ ) { 
            Node node = element.node(i); 
            if ( node instanceof Element ) { 
                treeWalk( (Element) node ); 
            } 
            else { 
                // do something.... 
            } 
        } 
    }

4.创建一个新的XML文档

import org.dom4j.Document; 
import org.dom4j.DocumentHelper; 
import org.dom4j.Element;

public class Foo {

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 Strachan" ); 
        
        Element author2 = root.addElement( "author" ) 
            .addAttribute( "name", "Bob" ) 
            .addAttribute( "location", "US" ) 
            .addText( "Bob McWhirter" );

return document; 
    } 
}

5.将XML文档写入文件

通过write()方法将一个XML文档写入文件是最简单的方式。 
    FileWriter out = new FileWriter( "foo.xml" ); 
    document.write( out ); 
    
  如果你想改变输出的格式,比如美观的格式(含缩进)和压缩的格式(不含缩进),可以使用XMLWriter类。

import org.dom4j.Document; 
import org.dom4j.io.OutputFormat; 
import org.dom4j.io.XMLWriter;

public class Foo {

public void write(Document document) throws IOException {

// lets write to a file 
        XMLWriter writer = new XMLWriter( 
            new FileWriter( "output.xml" ) 
        ); 
        writer.write( document ); 
        writer.close();

// Pretty print the document to System.out 
        OutputFormat format = OutputFormat.createPrettyPrint(); 
        writer = new XMLWriter( System.out, format ); 
        writer.write( document );

// Compact format to System.out 
        format = OutputFormat.createCompactFormat(); 
        writer = new XMLWriter( System.out, format ); 
        writer.write( document ); 
    } 
}

6.XML和String之间的相互转换

通过asXML()方法,你可以将一个Document,Attribute或Element对象转换成一个包含XML文本的字符串。 
        Document document = ...; 
        String text = document.asXML();

同样,通过DocumentHelper.parseText()方法,你也可以方便地将一个字符串形式的XML转换成一个Document对象。 
        String text = "<person> <name>James</name> </person>"; 
        Document document = DocumentHelper.parseText(text);

Dom4j官网解释实例的更多相关文章

  1. layui前端框架实例(修复官网数据接口异常问题)

    layui前端框架实例,官网的实例会提示数据接口异常,已修复. 主要是修改数据表格,做一个可以用的实例,可以选中,编辑,删除等. gitee地址:https://gitee.com/pingg2019 ...

  2. 【ABAP系列】SAP LSMW(摘自官网)

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[MM系列]SAP LSMW(摘自官网)   前 ...

  3. [ActionScript 3.0] Away3D 官网实例

    /* Dynamic tree generation and placement in a night-time scene Demonstrates: How to create a height ...

  4. activiti官网实例项目activiti-explorer之扩展流程节点属性2

    情景需求:需要查找activiti-explorer项目中获取流程id的方法,然后根据流程id获取相应字段在节点属性中添加内容. 大致流程:拿取整个流程id获取对应表单属性,在页面节点属性中展示对应表 ...

  5. Knockout官网实例在MVC下的实现-02,实现计次

    本篇使用Knockout在MVC下实现"Hello World",对应的官网实例在这里. 当次数达到3: View视图 页面包含三个部分:1.显示点击按钮的次数2.button按钮 ...

  6. Knockout官网实例在MVC下的实现-01,实现Hello world

    本篇使用Knockout在MVC下实现"Hello World",对应的官网实例在这里. View视图 Knockout的一个特点是:声明式绑定,即Declarative bind ...

  7. 官网实例详解-目录和实例简介-keras学习笔记四

    官网实例详解-目录和实例简介-keras学习笔记四 2018-06-11 10:36:18 wyx100 阅读数 4193更多 分类专栏: 人工智能 python 深度学习 keras   版权声明: ...

  8. vue3官网介绍,安装,创建一个vue实例

    前言:这一章主要是vue的介绍.安装.以及如何创建一个vue实例. 一.vue介绍 vue3中文官网:建议先自己看官网. https://v3.cn.vuejs.org/ vue是渐进式框架,渐进式指 ...

  9. BootStrap的一个标准框架的内容解释——来源于bootstrap官网

    <!DOCTYPE html><!--HTML5的定义--><html lang="zh-cn"> <head> <meta ...

随机推荐

  1. linux内核参数sysctl.conf,TCP握手ack,洪水攻击syn,超时关闭wait(转)

    http://www.xshell.net/linux/Linux_sysctl_conf.html 优化Linux内核sysctl.conf参数来提高服务器并发处理能力 Posted by 破冰 o ...

  2. 6_5.springboot2.x数据整合springData JPA

    1.配置文件 pom.xml <dependencies> <dependency> <groupId>org.springframework.boot</g ...

  3. Bubble Cup 12 - Finals Online Mirror, unrated, Div. 1

    Bubble Cup 12 - Finals Online Mirror, unrated, Div. 1 C. Jumping Transformers 我会状压 DP! 用 \(dp[x][y][ ...

  4. wpf 纯样式写按钮

    <!--自定义按钮样式--> <LinearGradientBrush x:Key="LinearGradientBlueBackground" EndPoint ...

  5. php断点续传之文件上传与文件下载

    下载: 原理: Http头的 Range.Content-Range()未启用单点登录GerenalRequest URL: http://www.demotest.com/php/fileDownl ...

  6. tensorflow识别验证码(1)-tensorflow安装,验证码生成

    什么是TensorFlow?  TensorFlow是Google开发的一款神经网络的Python外部的结构包, 也是一个采用数据流图来进行数值计算的开源软件库.TensorFlow 让我们可以先绘制 ...

  7. jvisualvm图解【转】

    jvisualvm图解[转]   http://blog.csdn.net/a19881029/article/details/8432368 jvisualvm能干什么:监控内存泄露,跟踪垃圾回收, ...

  8. JavaSE_12_序列化流和打印流

    1.1 序列化流概述 Java 提供了一种对象序列化的机制.用一个字节序列可以表示一个对象,该字节序列包含该对象的数据.对象的类型和对象中存储的属性等信息.字节序列写出到文件之后,相当于文件中持久保存 ...

  9. sql自定义日期函数,返回范围内日期和星期数表。

    Create function [dbo].[FUN_GenerateTime] ( @begin_date datetime, -- 起始时间 @end_date datetime -- 结束时间 ...

  10. 字符数组拷贝与strcpy函数

    代码: ],str2[]; ;i<;i++) { str1[i]='a'; } strcpy(str2,str1); 让找出错误的地方. 先来看下strcpy函数: 使用格式:char* str ...