您的位置:首页 > 其它

使用 dom4j 解析 XML

2010-02-01 20:57 218 查看
http://www.ibm.com/developerworks/cn/xml/x-dom4j.html

<!--
/* Font Definitions */
@font-face
{font-family:Wingdings;
panose-1:5 0 0 0 0 0 0 0 0 0;
mso-font-charset:2;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
{font-family:宋体;
panose-1:2 1 6 0 3 1 1 1 1 1;
mso-font-alt:SimSun;
mso-font-charset:134;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:3 135135232 16 0 262145 0;}
@font-face
{font-family:"\@宋体";
panose-1:2 1 6 0 3 1 1 1 1 1;
mso-font-charset:134;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:3 135135232 16 0 262145 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
text-align:justify;
text-justify:inter-ideograph;
mso-pagination:none;
font-size:10.5pt;
mso-bidi-font-size:12.0pt;
font-family:"Times New Roman";
mso-fareast-font-family:宋体;
mso-font-kerning:1.0pt;}
h1
{mso-margin-top-alt:auto;
margin-right:0cm;
mso-margin-bottom-alt:auto;
margin-left:0cm;
mso-pagination:widow-orphan;
mso-outline-level:1;
font-size:24.0pt;
font-family:宋体;
mso-bidi-font-family:宋体;
font-weight:bold;}
p
{mso-margin-top-alt:auto;
margin-right:0cm;
mso-margin-bottom-alt:auto;
margin-left:0cm;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:宋体;
mso-bidi-font-family:宋体;}
/* Page Definitions */
@page
{mso-page-border-surround-header:no;
mso-page-border-surround-footer:no;}
@page Section1
{size:595.3pt 841.9pt;
margin:72.0pt 90.0pt 72.0pt 90.0pt;
mso-header-margin:42.55pt;
mso-footer-margin:49.6pt;
mso-paper-source:0;
layout-grid:15.6pt;}
div.Section1
{page:Section1;}
/* List Definitions */
@list l0
{mso-list-id:1948538549;
mso-list-template-ids:966941842;}
@list l0:level1
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:36.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;
mso-ansi-font-size:10.0pt;
font-family:Symbol;}
ol
{margin-bottom:0cm;}
ul
{margin-bottom:0cm;}
-->

使用 dom4j 解析 XML

使用
domj4 API 创建与修改 XML 文档

dom4j 是一种解析 XML 文档的开放源代码 XML 框架。本文介绍如何使用包含在 dom4j 中的解析器创建并修改 XML 文档。

dom4j API 包含一个解析 XML 文档的工具。本文中将使用这个解析器创建一个示例 XML 文档。清单 1 显示了这个示例
XML 文档,catalog.xml。

清单 1. 示例 XML 文档(catalog.xml)

<?xml version="1.0" encoding="UTF-8"?>

<catalog>

<!--An XML Catalog-->

<?target instruction?>

<journal
title="XML Zone"

publisher="IBM developerWorks">

<article level="Intermediate"
date="December-2001">

<title>Java configuration with XML
Schema</title>

<author>

<firstname>Marcello</firstname>

<lastname>Vitaletti</lastname>

</author>

</article>

</journal>

</catalog>

然后使用同一个解析器修改 catalog.xml,清单 2 是修改后的 XML 文档,catalog-modified.xml。

清单 2. 修改后的
XML 文档(catalog-modified.xml)


<?xml version="1.0"
encoding="UTF-8"?>

<catalog>

<!--An XML catalog-->

<?target instruction?>

<journal
title="XML Zone"

publisher="IBM developerWorks">

<article level="Introductory"
date="October-2002">

<title>Create flexible and extensible
XML schemas</title>

<author>

<firstname>Ayesha</firstname>

<lastname>Malik</lastname>

</author>

</article>

</journal>

</catalog>


W3C DOM API 相比,使用 dom4j 所包含的解析器的好处是 dom4j 拥有本地的 XPath 支持。DOM 解析器不支持使用 XPath 选择节点。

本文包括以下几个部分:

预先设置

创建文档

修改文档

预先设置

这个解析器可以从 http://dom4j.org 获取。通过设置使 dom4j-1.4/dom4j-full.jar 能够在 classpath 中访问,该文件中包括 dom4j 类、XPath 引擎以及
SAX 和 DOM 接口。如果已经使用了 JAXP 解析器中包含的 SAX 和 DOM 接口,向
classpath 中增加 dom4j-1.4/dom4j.jar 。 dom4j.jar 包括 dom4j 类和 XPath 引擎,但是不含 SAX 与
DOM 接口。









回页首

创建文档

本节讨论使用 dom4j API 创建 XML 文档的过程,并创建示例 XML 文档 catalog.xml。

使用 import 语句导入 dom4j API 类:

import org.dom4j.Document;

import org.dom4j.DocumentHelper;

import org.dom4j.Element;

使用 DocumentHelper 类创建一个文档实例。 DocumentHelper 是生成 XML 文档节点的 dom4j API 工厂类。

Document
document = DocumentHelper.createDocument();

使用 addElement() 方法创建根元素 catalog 。 addElement() 用于向 XML 文档中增加元素。

Element catalogElement =
document.addElement("catalog");


catalog 元素中使用 addComment() 方法添加注释“An XML catalog”。

catalogElement.addComment("An XML
catalog");


catalog 元素中使用 addProcessingInstruction() 方法增加一个处理指令。

catalogElement.addProcessingInstruction("target","text");


catalog 元素中使用 addElement() 方法增加
journal 元素。

Element journalElement =
catalogElement.addElement("journal");

使用 addAttribute() 方法向 journal 元素添加 title 和 publisher 属性。

journalElement.addAttribute("title",
"XML Zone");

journalElement.addAttribute("publisher", "IBM
developerWorks");


article 元素中添加 journal 元素。

Element articleElement=journalElement.addElement("article");


article 元素增加 level 和 date 属性。

articleElement.addAttribute("level",
"Intermediate");

articleElement.addAttribute("date",
"December-2001");


article 元素中增加 title 元素。

Element
titleElement=articleElement.addElement("title");

使用 setText() 方法设置 article 元素的文本。

titleElement.setText("Java configuration with XML
Schema");


article 元素中增加 author 元素。

Element
authorElement=articleElement.addElement("author");


author 元素中增加 firstname 元素并设置该元素的文本。

Element
firstNameElement=authorElement.addElement("firstname");

firstNameElement.setText("Marcello");


author 元素中增加 lastname 元素并设置该元素的文本。

Element
lastNameElement=authorElement.addElement("lastname");

lastNameElement.setText("Vitaletti");

可以使用 addDocType() 方法添加文档类型说明。

document.addDocType("catalog",
null,"file://c:/Dtds/catalog.dtd");

这样就向 XML 文档中增加文档类型说明:

<!DOCTYPE catalog SYSTEM
"file://c:/Dtds/catalog.dtd">

如果文档要使用文档类型定义(DTD)文档验证则必须有 Doctype。

XML 声明 <?xml version="1.0"
encoding="UTF-8"?> 自动添加到 XML 文档中。

清单 3 所示的例子程序 XmlDom4J.java 用于创建 XML 文档 catalog.xml。

清单 3. 生成 XML 文档 catalog.xml 的程序(XmlDom4J.java)

import org.dom4j.Document;

import org.dom4j.DocumentHelper;

import org.dom4j.Element;

import org.dom4j.io.XMLWriter;

import java.io.*;

public class XmlDom4J{

public void generateDocument(){

Document document = DocumentHelper.createDocument();

Element
catalogElement = document.addElement("catalog");

catalogElement.addComment("An XML Catalog");

catalogElement.addProcessingInstruction("target","text");

Element
journalElement =
catalogElement.addElement("journal");

journalElement.addAttribute("title", "XML Zone");

journalElement.addAttribute("publisher", "IBM
developerWorks");

Element
articleElement=journalElement.addElement("article");

articleElement.addAttribute("level",
"Intermediate");

articleElement.addAttribute("date",
"December-2001");

Element
titleElement=articleElement.addElement("title");

titleElement.setText("Java configuration with XML Schema");

Element
authorElement=articleElement.addElement("author");

Element
firstNameElement=authorElement.addElement("firstname");

firstNameElement.setText("Marcello");

Element
lastNameElement=authorElement.addElement("lastname");

lastNameElement.setText("Vitaletti");

document.addDocType("catalog",

null,"file://c:/Dtds/catalog.dtd");

try{

XMLWriter
output = new XMLWriter(

new
FileWriter( new File("c:/catalog/catalog.xml") ));

output.write( document );

output.close();

}

catch(IOException e){System.out.println(e.getMessage());}

}

public static void main(String[] argv){

XmlDom4J dom4j=new XmlDom4J();

dom4j.generateDocument();

}}

这一节讨论了创建 XML 文档的过程,下一节将介绍使用 dom4j API 修改这里创建的 XML 文档。









回页首

修改文档

这一节说明如何使用 dom4j API 修改示例 XML 文档 catalog.xml。

使用 SAXReader 解析 XML 文档
catalog.xml:

SAXReader saxReader = new SAXReader();

Document
document = saxReader.read(inputXml);

SAXReader 包含在 org.dom4j.io 包中。

inputXml 是从 c:/catalog/catalog.xml 创建的 java.io.File。使用 XPath 表达式从 article 元素中获得 level 节点列表。如果 level 属性值是“Intermediate”则改为“Introductory”。

List list =
document.selectNodes("//article/@level" );

Iterator
iter=list.iterator();

while(iter.hasNext()){

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

if(attribute.getValue().equals("Intermediate"))

attribute.setValue("Introductory");

}

获取 article 元素列表,从 article 元素中的 title 元素得到一个迭代器,并修改 title 元素的文本。

list = document.selectNodes("//article" );

iter=list.iterator();

while(iter.hasNext()){

Element element=(Element)iter.next();

Iterator
iterator=element.elementIterator("title");

while(iterator.hasNext()){

Element
titleElement=(Element)iterator.next();

if(titleElement.getText().equals("Java configuration with XML
Schema"))

titleElement.setText("Create
flexible and extensible XML schema");

}}

通过和 title 元素类似的过程修改 author 元素。

清单 4 所示的示例程序 Dom4JParser.java 用于把 catalog.xml 文档修改成 catalog-modified.xml 文档。

清单 4. 用于修改
catalog.xml 的程序(Dom4Jparser.java)


import org.dom4j.Document;

import org.dom4j.Element;

import org.dom4j.Attribute;

import java.util.List;

import java.util.Iterator;

import org.dom4j.io.XMLWriter;

import java.io.*;

import org.dom4j.DocumentException;

import org.dom4j.io.SAXReader;

public class Dom4JParser{

public void modifyDocument(File
inputXml){

try{

SAXReader
saxReader = new SAXReader();

Document
document = saxReader.read(inputXml);

List list =
document.selectNodes("//article/@level" );

Iterator
iter=list.iterator();

while(iter.hasNext()){

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

if(attribute.getValue().equals("Intermediate"))

attribute.setValue("Introductory");

}

list =
document.selectNodes("//article/@date" );

iter=list.iterator();

while(iter.hasNext()){

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

if(attribute.getValue().equals("December-2001"))

attribute.setValue("October-2002");

}

list =
document.selectNodes("//article" );

iter=list.iterator();

while(iter.hasNext()){

Element element=(Element)iter.next();

Iterator
iterator=element.elementIterator("title");

while(iterator.hasNext()){

Element
titleElement=(Element)iterator.next();

if(titleElement.getText().equals("Java configuration with XML

Schema"))

titleElement.setText("Create flexible and extensible XML
schema");

}

}

list =
document.selectNodes("//article/author" );

iter=list.iterator();

while(iter.hasNext()){

Element
element=(Element)iter.next();

Iterator
iterator=element.elementIterator("firstname");

while(iterator.hasNext()){

Element
firstNameElement=(Element)iterator.next();

if(firstNameElement.getText().equals("Marcello"))

firstNameElement.setText("Ayesha");

}

}

list =
document.selectNodes("//article/author" );

iter=list.iterator();

while(iter.hasNext()){

Element
element=(Element)iter.next();

Iterator
iterator=element.elementIterator("lastname");

while(iterator.hasNext()){

Element
lastNameElement=(Element)iterator.next();

if(lastNameElement.getText().equals("Vitaletti"))

lastNameElement.setText("Malik");

}

}

XMLWriter
output = new XMLWriter(

new
FileWriter( new File("c:/catalog/catalog-modified.xml") ));

output.write( document );

output.close();

}

catch(DocumentException e)

{

System.out.println(e.getMessage());

}

catch(IOException e){

System.out.println(e.getMessage());

}

}

public static
void main(String[] argv){

Dom4JParser
dom4jParser=new Dom4JParser();

dom4jParser.modifyDocument(new
File("c:/catalog/catalog.xml"));

}

}

这一节说明了如何使用 dom4j 中的解析器修改示例 XML 文档。这个解析器不使用 DTD 或者模式验证 XML 文档。如果 XML 文档需要验证,可以解释用 dom4j 与 JAXP SAX 解析器。

结束语

包含在 dom4j 中的解析器是一种用于解析 XML 文档的非验证性工具,可以与JAXP、Crimson 或
Xerces 集成。本文说明了如何使用该解析器创建和修改 XML 文档

使用 dom4j 解析 XML

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: