dom4j快速入门

Quick Start Guide

The Quick Start Guide will hopefully show you how to do the basic operations in dom4j.

Parsing XML

One of the first things you‘ll probably want to do is to parse an XML document of some kind. This is easy to do in dom4j. The following code demonstrates how to this.

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;

}

}

Using Iterators

A document can be navigated using a variety of methods that return standard Java Iterators. For example

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

}

}

Powerful Navigation with XPath

In dom4j XPath expressions can be evaluated on the Document or on any Node in the tree (such as Attribute, Element or ProcessingInstruction). This allows complex navigation throughout the document with a single line of code. For example.

public void bar(Document document) {

List list = document.selectNodes( "//foo/bar" );

Node node = document.selectSingleNode( "//foo/bar/author" );

String name = node.valueOf( "@name" );

}

For example if you wish to find all the hypertext links in an XHTML document the following code would do the trick.

public void findLinks(Document document) throws DocumentException {

List list = document.selectNodes( "//a/@href" );

for (Iterator iter = list.iterator(); iter.hasNext(); ) {

Attribute attribute = (Attribute) iter.next();

String url = attribute.getValue();

}

}

If you need any help learning the XPath language we highly recommend the Zvon tutorial which allows you to learn by example.

Fast Looping

If you ever have to walk a large XML document tree then for performance we recommend you use the fast looping method which avoids the cost of creating an Iterator object for each loop. For example

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....

}

}

}

Creating a new XML document

Often in dom4j you will need to create a new document from scratch. Here‘s an example of doing that.

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;

}

}

Writing a document to a file

A quick and easy way to write a Document (or any Node) to a Writer is via the write() method. FileWriter out = new FileWriter( "foo.xml" ); document.write( out );

If you want to be able to change the format of the output, such as pretty printing or a compact format, or you want to be able to work with Writer objects or OutputStream objects as the destination, then you can use the XMLWriter class. 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 );

}

}

Converting to and from Strings

If you have a reference to a Document or any other Node such as an Attribute or Element, you can turn it into the default XML text via the asXML() method.

Document document = …;

String text = document.asXML();

If you have some XML as a String you can parse it back into a Document again using the helper method DocumentHelper.parseText() String text = "<person> <name>James</name> </person>"; Document document = DocumentHelper.parseText(text);

Styling a Document with XSLT

Applying XSLT on a Document is quite straightforward using the JAXP API from Sun. This allows you to work against any XSLT engine such as Xalan or SAXON. Here is an example of using JAXP to create a transformer and then applying it to a Document. import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory;

import org.dom4j.Document;

import org.dom4j.io.DocumentResult;

import org.dom4j.io.DocumentSource;

public class Foo {

public Document styleDocument(

Document document,

String stylesheet

) throws Exception {

// load the transformer using JAXP

TransformerFactory factory = TransformerFactory.newInstance();

Transformer transformer = factory.newTransformer(

new StreamSource( stylesheet )

);

// now lets style the given document

DocumentSource source = new DocumentSource( document );

DocumentResult result = new DocumentResult();

transformer.transform( source, result );

// return the transformed document

Document transformedDoc = result.getDocument();

return transformedDoc;

}

}

时间: 2024-07-29 01:54:56

dom4j快速入门的相关文章

JAVAWEB开发之Struts2详解(一)——Struts2框架介绍与快速入门、流程分析与工具配置以及Struts2的配置以及Action和Result的详细使用

Struts2框架介绍 三大框架:是企业主流JavaEE开发的一套架构.Struts2 + Spring + Hibernate 什么是框架?为什么要学习框架? 框架是实现部分功能的代码(半成品),使用框架简化企业级软件开发. Struts2与MVC? Struts是一款优秀的MVC框架 MVC:是一种思想,是一种模式,将软件分为Model模型.View视图.Controller控制器 JAVAEE软件三层架构:web层(表现层).业务逻辑层.数据持久层(Sun提供javaEE开发规范) Jav

Schema的快速入门

Schema的快速入门 如果是简单元素直接  <element name="" type=""></element> Schema开发过程: Sax 解的析原理 解析xml有两种技术   dom  和sax 4使用jaxp的sax方式解析xml **Sax方法不能实现增删改查,只能做查询操作 **打印出整个文档 **执行parse方法,第一个参数xml路径,第二个参数  是事件处理器 **创建一个类,继承事件处理器的类 **重写里面的三个方法

笔记:Spring Cloud Zuul 快速入门

Spring Cloud Zuul 实现了路由规则与实例的维护问题,通过 Spring Cloud Eureka 进行整合,将自身注册为 Eureka 服务治理下的应用,同时从 Eureka 中获取了所有其他微服务的实例信息,这样的设计非常巧妙的将服务治理体系中维护的实例信息利用起来,使得维护服务实例的工作交给了服务治理框架自动完成,而对路由规则的维护,默认会将通过以服务名作为 ContextPath 的方式来创建路由映射,也可以做一些特别的配置,对于签名校验.登录校验等在微服务架构中的冗余问题

javaweb-html快速入门

本文主要是进行HTML简单介绍(详细的属性查帮助文档就行了,这里主要为快速入门,赶时间,在最短的时间中看明白一个html文件的代码(如果能称之为代码的话)详细的样式表,布局啥的有时间再研究吧) HTML 1.html的简介 1.1,html的全称:HyperText Mark-up Language ,超文本标记型语言,是网页的语言. 超文本:比文本更加强大(后面还会讲到XML,可扩展标记性语言) 标记:就是标签,html所有操作都是通过标签直接或间接的操作(把需要操作的数据通过标签封装起来)

crosswalk 快速入门,利用WebRTC(html)开始开发视频通话

crosswalk 快速入门,利用WebRTC(html)开始开发视频通话 安装Python 从http://www.python.org/downloads/ 下载安装程序 安装完后,再添加到环境变量. 安装Oracle JDK 下载页面: http://www.oracle.com/technetwork/java/javase/downloads/ 选择要下载的Java版本(推荐Java 7). 选择一个JDK下载并接受许可协议. 一旦下载,运行安装程序. 安装Ant Ant:下载http

bash编程快速入门

首先,我们简单的介绍一下bash,bash是GNU计划编写的Unixshell,它是许多Linux平台上的内定shell,它提供了用户与系统的很好的交互,对于系统运维人员,bash的地位是举足轻重的,bash编程能很快处理日常的任务 bash入门,一个最简单的bash例子 #vim hello.sh #!/bin/bash #This is the first example of the bash #echo "Hello world" 下面,我们就这个简单的bash 脚本来介绍一下

定时器(Quartz)快速入门

Quartz概述 Quartz中的触发器 Quartz中提供了两种触发器,分别是CronTrigger和SimpleTrigger. SimpleTrigger 每 隔若干毫秒来触发纳入进度的任务.因此,对于夏令时来说,根本不需要做任何特殊的处理来"保持进度".它只是简单地保持每隔若干毫秒来触发一次,无论你的 SimpleTrigger每隔10秒触发一次还是每隔15分钟触发一次,还是每隔24小时触发一次. CronTrigger 在特定"格林日历"时刻触发纳入进程的

vue.js--60分钟快速入门

Vue.js--60分钟快速入门 Vue.js是当下很火的一个JavaScript MVVM库,它是以数据驱动和组件化的思想构建的.相比于Angular.js,Vue.js提供了更加简洁.更易于理解的API,使得我们能够快速地上手并使用Vue.js. 本文摘自:http://www.cnblogs.com/keepfool/p/5619070.html 如果你之前已经习惯了用jQuery操作DOM,学习Vue.js时请先抛开手动操作DOM的思维,因为Vue.js是数据驱动的,你无需手动操作DOM

Netty5快速入门及实例视频教程(整合Spring)

Netty5快速入门及实例视频教程+源码(整合Spring) https://pan.baidu.com/s/1pL8qF0J 01.传统的Socket分析02.NIO的代码分析03.对于NIO的一些疑惑04.Netty服务端HelloWorld入门05.Netty服务端入门补充06.Netty客户端入门07.如何构建一个多线程NIO系统08.Netty源码分析一09.Netty源码分析二10.Netty5服务端入门案例11.Netty5客户端入门案例12.单客户端多连接程序13.Netty学习