---
title: "java解析xml之三:使用domj4"
author: "sysu_zeh"
date: "2007-09-01T22:06:00Z"
tags: ["IBM", "IE", "Java", "PHP", "XML"]
slug: "java-xml-domj4"
draft: false
lastmod: "2007-09-01T22:06:00Z"
id: 119310
url: "https://sysu-zeh.iteye.com/blog/119310"
---

**一.简介**

    DOM4J是dom4j.org出品的一个开源XML解析包。Dom4j是一个易用的、开源的库，用于XML，XPath和XSLT。它应用于Java平台，采用了Java集合框架并完全支持DOM，SAX和JAXP。DOM4J最大的特色是使用大量的接口，这也是它被认为比JDOM灵活的主要原因。

**二.安装dom4j**

1.下载dom4j：[http://sourceforge.net/project/showfiles.php?group\_id=16035](http://sourceforge.net/project/showfiles.php?group_id=16035)

2.安装dom4j：将解压后的dom4j-full.jar文件放置到项目的类路径中去，也可以作为附加包添加到项目中。

**三.实例**

**1.所需xml文件**

catalog.xml

01. xml version="1.0" encoding="GBK"?&gt;
02. &lt;catalog&gt;
03. target text?&gt;
04. &lt;journal title="XML Zone" publisher="IBM developerWorks"&gt;
05. &lt;article level="Intermediate" date="December-2001"&gt;
06. &lt;title&gt;Java configuration with XML Schematitle&gt;
07. &lt;author&gt;
08. &lt;firstname&gt;Marcellofirstname&gt;
09. &lt;lastname&gt;Vitalettilastname&gt;
10. author&gt;
11. article&gt;
12. journal&gt;
13. catalog&gt;

**2.修改xml文件**

01. package domj4Parser;
02. import java.io.\*;
03. //导入dom4j API类
04. import org.dom4j.Document;
05. import org.dom4j.DocumentHelper;
06. import org.dom4j.Element;
07. import org.dom4j.io.XMLWriter;
08. public class XmlDom4J{
09. public void generateDocument(){
10. //使用 DocumentHelper 类创建一个文档实例
11. //DocumentHelper 是生成 XML 文档节点的 dom4j API 工厂类
12. Document document = DocumentHelper.createDocument();
13. //使用 addElement() 方法创建根元素 catalog
14. //addElement() 用于向 XML 文档中增加元素
15. Element catalogElement = document.addElement("catalog");
16. //在 catalog 元素中使用 addComment() 方法添加注释"An XML catalog"
17. catalogElement.addComment("An XML Catalog");
18. //在 catalog 元素中使用 addProcessingInstruction() 方法增加一个处理指令
19. catalogElement.addProcessingInstruction("target","text");
20. //在 catalog 元素中使用 addElement() 方法增加 journal 元素
21. Element journalElement = catalogElement.addElement("journal");
22. //使用 addAttribute() 方法向 journal 元素添加 title 和 publisher 属性
23. journalElement.addAttribute("title", "XML Zone");
24. journalElement.addAttribute("publisher", "IBM developerWorks");
25. //向 article 元素中添加 journal 元素
26. Element articleElement=journalElement.addElement("article");
27. //为 article 元素增加 level 和 date 属性
28. articleElement.addAttribute("level", "Intermediate");
29. articleElement.addAttribute("date", "December-2001");
30. //向 article 元素中增加 title 元素
31. Element titleElement=articleElement.addElement("title");
32. //使用 setText() 方法设置 article 元素的文本
33. titleElement.setText("Java configuration with XML Schema");
34. //在 article 元素中增加 author 元素
35. Element authorElement=articleElement.addElement("author");
36. //在 author 元素中增加 firstname 元素并设置该元素的文本
37. Element firstNameElement=authorElement.addElement("firstname");
38. firstNameElement.setText("Marcello");
39. //在 author 元素中增加 lastname 元素并设置该元素的文本
40. Element lastNameElement=authorElement.addElement("lastname");
41. lastNameElement.setText("Vitaletti");
42. //可以使用 addDocType() 方法添加文档类型说明
43. //document.addDocType("catalog",null,"catalog.dtd");
44. try{
45. XMLWriter output = new XMLWriter(
46. new FileWriter(new File("xmlFile/catalog.xml")));
47. output.write(document);
48. output.close();
49. }
50. catch(IOException e){
51. System.out.println(e.getMessage());
52. }
53. }
54. public static void main(String\[] argv){
55. XmlDom4J dom4j=new XmlDom4J();
56. dom4j.generateDocument();
57. }
58. }

**3.生成xml文件**

001. package domj4Parser;
002. import java.util.List;
003. import java.util.Iterator;
004. import java.io.\*;
005. //导入 dom4j API 类
006. import org.dom4j.Document;
007. import org.dom4j.Element;
008. import org.dom4j.Attribute;
009. import org.dom4j.Node;
010. import org.dom4j.io.OutputFormat;
011. import org.dom4j.io.XMLWriter;
012. import org.dom4j.DocumentException;
013. import org.dom4j.io.SAXReader;
014. public class Dom4Jparser{
015. public void modifyDocument(File inputXml){
016. try{
017. //使用 SAXReader 解析 XML 文档 catalog.xml
018. SAXReader saxReader = new SAXReader();
019. //inputXml 是从 catalog.xml 创建的 java.io.File
020. Document document = saxReader.read(inputXml);
021. //使用 XPath 表达式从 article 元素中获得 level 节点列表
022. List list = document.selectNodes("//article/@level");
023. Iterator iter=list.iterator();
024. while(iter.hasNext()){
025. //如果 level 属性值是"Intermediate"则改为"Introductory"
026. Attribute attribute=(Attribute)iter.next();
027. if(attribute.getValue().equals("Intermediate"))
028. attribute.setValue("Introductory");
029. }
030. list = document.selectNodes("//article/@date" );
031. iter=list.iterator();
032. while(iter.hasNext()){
033. Attribute attribute=(Attribute)iter.next();
034. if(attribute.getValue().equals("December-2001"))
035. attribute.setValue("October-2002");
036. }
037. //获取 article 元素列表
038. list = document.selectNodes("//article" );
039. iter=list.iterator();
040. while(iter.hasNext()){
041. Element element=(Element)iter.next();
042. //使用Visitor模式遍历子节点
043. element.accept(new MyVisitor());
044. //从 article 元素中的 title 元素得到一个迭代器
045. Iterator iterator=element.elementIterator("title");
046. while(iterator.hasNext()){
047. Element titleElement=(Element)iterator.next();
048. //并修改 title 元素的文本
049. if(titleElement.getText().equals("Java configuration with XMLSchema"))
050. titleElement.setText("Create flexible and extensible XML schema");
051. }
052. }
053. list = document.selectNodes("//article/author" );
054. iter=list.iterator();
055. while(iter.hasNext()){
056. Element element=(Element)iter.next();
057. Iterator iterator=element.elementIterator("firstname");
058. while(iterator.hasNext()){
059. Element firstNameElement=(Element)iterator.next();
060. if(firstNameElement.getText().equals("Marcello"))
061. firstNameElement.setText("Ayesha");
062. }
063. }
064. list = document.selectNodes("//article/author" );
065. iter=list.iterator();
066. while(iter.hasNext()){
067. Element element=(Element)iter.next();
068. Iterator iterator=element.elementIterator("lastname");
069. while(iterator.hasNext()){
070. Element lastNameElement=(Element)iterator.next();
071. if(lastNameElement.getText().equals("Vitaletti"))
072. lastNameElement.setText("Malik");
073. }
074. }
075. XMLWriter output = new XMLWriter(
076. new FileWriter( new File("xmlFile/catalog-modified.xml")));
077. output.write(document);
078. output.close();
079. }
080. catch(DocumentException e){
081. e.printStackTrace();
082. }
083. catch(IOException e){
084. System.out.println(e.getMessage());
085. }
086. }
087. public void treeWalk(Element element) {
088. for (int i = 0,size = element.nodeCount();i &lt; size;i++){
089. Node node = element.node(i);
090. if (node instanceof Element) {
091. treeWalk((Element) node);
092. }
093. else { /* do something....\*/}
094. }
095. }
096. //处理中文问题
097. public int formatXMLFile(String filename){
098. int returnValue = 0;
099. try{
100. SAXReader saxReader = new SAXReader();
101. Document document = saxReader.read(new File(filename));
102. XMLWriter output = null;
103. /\** 格式化输出,类型IE浏览一样 \*/
104. OutputFormat format = OutputFormat.createPrettyPrint();
105. /\** 指定XML字符集编码 \*/
106. format.setEncoding("GBK");
107. output = new XMLWriter(new FileWriter(new File(filename)),format);
108. output.write(document);
109. output.close();
110. /\** 执行成功,需返回1 \*/
111. returnValue = 1;
112. }
113. catch(Exception ex){
114. ex.printStackTrace();
115. }
116. return returnValue;
117. }
118. public static void main(String\[] argv){
119. Dom4Jparser dom4jParser=new Dom4Jparser();
120. dom4jParser.modifyDocument(new File("xmlFile/catalog.xml"));
121. dom4jParser.formatXMLFile("xmlFile/catalog.xml");
122. }
123. }

**4.使用Visitor模式**

01. package domj4Parser;
02. import org.dom4j.Attribute;
03. import org.dom4j.Element;
04. import org.dom4j.VisitorSupport;
05. //Visitor模式
06. public class MyVisitor extends VisitorSupport {
07. public void visit(Element element){
08. System.out.println(element.getName());
09. }
10. public void visit(Attribute attr){
11. System.out.println(attr.getName());
12. }
13. }