这就是JDOM设计者的目标。如果你曾经使用过烦人的SAX或是DOM来处理XML,你就会知道为什么要有JDOM或者是JAXB。在今年(2002)的JavaOne会议上JDOM的主要创始人Jason Hunter有一篇精彩的演讲介绍了JDOM技术,题目就是JDOM Makes XML Easy。
获得并安装JDOM
在http://jdom.org可以下载JDOM的最新版本。以 JDOM 1.0的2进制版本为例。下载后解压缩,JDOM的jar文件就是build目录下的文件jdom.jar,将之加入类路径。另外JDOM还需要lib目录下那些jar文件如xerces.jar,jaxp.jar的支持。如果在使用中出现以下错误:
java.lang.NoSuchMethodError
或
java.lang.NoClassDefFoundError: org/xml/sax/SAXNotRecognizedException
你需要保证xerces.jar文件在CLASSPATH中位于其他XML类,如JAXP或Crimson之前,这些类文件,包括以前老版本的xerces,可能不支持SAX2.0或DOM Level 2。于是导致了上面的错误。
一个简单的例子
JDOM的处理方式有些类似于DOM,但它主要是用SAX实现的,你不必担心处理速度和内存的问题。另外,JDOM中几乎没有接口,的类全部是实实在在的类,没有类工厂类的。
下面是实例用的XML文件: MyXml.xml
<?xml version="1.0" encoding="utf-8"?>
<书库>
<书>
<书名>Java编程入门</书名>
<作者>张三</作者>
<出版社>电子出版社</出版社>
<价格>35.0</价格>
<出版日期>2002-10-07</出版日期>
</书>
<书>
<书名>XML在Java中的应用</书名>
<作者>李四</作者>
<出版社>希望出版社</出版社>
<价格>92.0</价格>
<出版日期>2002-10-07</出版日期>
</书>
</书库>
下面是操作XML文件的Bean: XmlBean.java
package jdom.test;
/**
* XML的读写操作Bean
*/
import java.io.*;
import java.util.*;
import org.jdom.*;
import org.jdom.output.*;
import org.jdom.input.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class XmlBean {
private String bookname, author, pub, price, pubdate;
public String getbookname() {
return bookname;
}
public String getauthor() {
return author;
}
public String getpub() {
return pub;
}
public String getprice() {
return price;
}
public String getpubdate() {
return pubdate;
}
public void setbookname(String bookname) {
this.bookname = bookname;
}
public void setauthor(String author) {
this.author = author;
}
public void setpub(String pub) {
this.pub = pub;
}
public void setprice(String price) {
this.price = price;
}
public void setpubdate(String pubdate) {
this.pubdate = pubdate;
}
public XmlBean() {
}
/**
* 读取XML文件所有信息
*/
public Vector LoadXML(String path) throws Exception {
Vector xmlVector = null;
FileInputStream fi = null;
try {
fi = new FileInputStream(path);
xmlVector = new Vector();
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(fi);
Element root = doc.getRootElement(); // 得到根元素
List books = root.getChildren(); // 得到根元素所有子元素的集合
Element book = null;
XmlBean xml = null;
for (int i = 0; i < books.size(); i++) {
xml = new XmlBean();
book = (Element) books.get(i); // 得到第一本书元素
xml.setbookname(book.getChild("书名").getText());
xml.setauthor(book.getChild("作者").getText());
xml.setpub(book.getChild("出版社").getText());
xml.setprice(book.getChild("价格").getText());
xml.setpubdate(book.getChild("出版日期").getText());
xmlVector.add(xml);
}
} catch (Exception e) {
System.err.println(e + "error");
} finally {
try {
fi.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return xmlVector;
}
/**
* 删除XML文件指定信息
*/
public static void DelXML(HttpServletRequest request) throws Exception {
FileInputStream fi = null;
FileOutputStream fo = null;
try {
request.setCharacterEncoding("GBK");
String path = request.getParameter("path");
int xmlid = Integer.parseInt(request.getParameter("id"));
fi = new FileInputStream(path);
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(fi);
Element root = doc.getRootElement(); // 得到根元素
List books = root.getChildren(); // 得到根元素所有子元素的集合
books.remove(xmlid);// 删除指定位置的子元素
// String indent = " ";
// boolean newLines = true;
// XMLOutputter outp = new XMLOutputter(indent, newLines, "GBK");
Format format = Format.getPrettyFormat();
format.setIndent(" ");
format.setEncoding("utf-8");
XMLOutputter outp = new XMLOutputter(format);
fo = new FileOutputStream(path);
outp.output(doc, fo);
} catch (Exception e) {
System.err.println(e + "error");
} finally {
try {
fi.close();
fo.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 添加XML文件指定信息
*/
public static void AddXML(HttpServletRequest request) throws Exception {
FileInputStream fi = null;
FileOutputStream fo = null;
try {
request.setCharacterEncoding("GBK");
String path = request.getParameter("path");
fi = new FileInputStream(path);
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(fi);
Element root = doc.getRootElement(); // 得到根元素
List books = root.getChildren(); // 得到根元素所有子元素的集合
String bookname = request.getParameter("bookname");
String author = request.getParameter("author");
String price = request.getParameter("price");
String pub = request.getParameter("pub");
String pubdate = request.getParameter("pubdate");
// Text newtext;
Element newbook = new Element("书");
Element newname = new Element("书名");
newname.setText(bookname);
newbook.addContent(newname);
Element newauthor = new Element("作者");
newauthor.setText(author);
newbook.addContent(newauthor);
Element newpub = new Element("出版社");
newpub.setText(pub);
newbook.addContent(newpub);
Element newprice = new Element("价格");
newprice.setText(price);
newbook.addContent(newprice);
Element newdate = new Element("出版日期");
newdate.setText(pubdate);
newbook.addContent(newdate);
books.add(newbook);// 增加子元素
// String indent = " ";
// boolean newLines = true;
// XMLOutputter outp = new XMLOutputter(indent, newLines, "GBK");
Format format = Format.getPrettyFormat();
format.setIndent(" ");
format.setEncoding("utf-8");
XMLOutputter outp = new XMLOutputter(format);
fo = new FileOutputStream(path);
outp.output(doc, fo);
} catch (Exception e) {
System.err.println(e + "error");
} finally {
try {
fi.close();
fo.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 修改XML文件指定信息
*/
public static void EditXML(HttpServletRequest request) throws Exception {
FileInputStream fi = null;
FileOutputStream fo = null;
try {
request.setCharacterEncoding("GBK");
String path = request.getParameter("path");
int xmlid = Integer.parseInt(request.getParameter("id"));
fi = new FileInputStream(path);
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(fi);
Element root = doc.getRootElement(); // 得到根元素
List books = root.getChildren(); // 得到根元素所有子元素的集合
Element book = (Element) books.get(xmlid);
String bookname = request.getParameter("bookname");
String author = request.getParameter("author");
String price = request.getParameter("price");
String pub = request.getParameter("pub");
String pubdate = request.getParameter("pubdate");
// Text newtext;
Element newname = book.getChild("书名");
newname.setText(bookname);// 修改书名为新的书名
Element newauthor = book.getChild("作者");
newauthor.setText(author);
Element newpub = book.getChild("出版社");
newpub.setText(pub);
Element newprice = book.getChild("价格");
newprice.setText(price);
Element newdate = book.getChild("出版日期");
newdate.setText(pubdate);
// books.set(xmlid,book);//修改子元素
// String indent = " ";
// boolean newLines = true;
// XMLOutputter outp = new XMLOutputter(indent, newLines, "GBK");
Format format = Format.getPrettyFormat();
format.setIndent(" ");
format.setEncoding("utf-8");
XMLOutputter outp = new XMLOutputter(format);
fo = new FileOutputStream(path);
outp.output(doc, fo);
} catch (Exception e) {
System.err.println(e + "error");
} finally {
try {
fi.close();
fo.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
下面是操作的jsp文件: test.jsp
<%@ page contentType="text/html;charset=GBK"%>
<%@ page language="java" import="java.util.*,jdom.test.*"%>
<html>
<head>
<title>读取XML文件资料</title>
</head>
<body>
<h3 align="center">JDOM操作XML文件</h3>
<p align="center">读取XML文件中的所有资料</p>
<center>
<table border="1" cellpadding="0" cellspacing="1"
style="border-collapse: collapse" width="80%" id="AutoNumber1">
<tr>
<td align="center" width="92">书名</td>
<td align="center" width="92">作者</td>
<td align="center" width="92">出版社</td>
<td align="center" width="92">价格</td>
<td align="center" width="92">出版日期</td>
<td align="center" width="94">操作</td>
</tr>
</table>
<%
String path = application.getRealPath("/JDOM/MyXml.xml");
XmlBean xml = new XmlBean();
Vector xmlall = xml.LoadXML(path);
for (int i = 0; i < xmlall.size(); i++) {
xml = (XmlBean) xmlall.elementAt(i);
/**out.println("书名:"+xml.getbookname()+"<br>");
out.println("作者:"+xml.getauthor()+"<br>");
out.println("出版社:"+xml.getpub()+"<br>");
out.println("价格:"+xml.getprice()+"<br>");
out.println("出版日期:"+xml.getpubdate()+"<br><br>");
*/
%>
<table border="1" cellpadding="0" cellspacing="1"
style="border-collapse: collapse" width="80%" id="AutoNumber2">
<tr>
<td align="center" width="92"><%=xml.getbookname()%></td>
<td align="center" width="92"><%=xml.getauthor()%></td>
<td align="center" width="92"><%=xml.getpub()%></td>
<td align="center" width="92"><%=xml.getprice()%></td>
<td align="center" width="92"><%=xml.getpubdate()%></td>
<td align="center" width="94"><a
href="xmlaction.jsp?act=del&id=<%=i%>&path=<%=path%>">删除</a></td>
</tr>
</table>
<%}%></center>
<form method="POST" action="xmlaction.jsp">
<p align="center"><input type="radio" value="add" checked name="act">添加资料
<input type="radio" value="edit" name="act">编辑资料 序 号:<select size="1"
name="id">
<%for (int i = 0; i < xmlall.size(); i++) {%>
<option value="<%=i%>">第<%=i + 1%>条</option>
<%}%>
</select><br>
书 名:<input type="text" name="bookname" size="20"><br>
作 者:<input type="text" name="author" size="20"><br>
出版社:<input type="text" name="pub" size="20"><br>
价 格:<input type="text" name="price" size="20"><br>
日 期:<input type="text" name="pubdate" size="20"></p>
<input type="hidden" name="path" value="<%=path%>">
<p align="center"><input type="submit" value="提交" name="B1"><input
type="reset" value="重置" name="B2"></p>
</form>
</body>
</html>
下面是处理上一文件提交的jsp文件: xmlation.jsp
<%@ page contentType="text/html;charset=GBK"%>
<%@ page language="java" import="jdom.test.*"%>
<%if (request.getParameter("act") != null
&& request.getParameter("act").equals("add")) {
XmlBean.AddXML(request);
out.println("<p align='center'><br><br>添加成功<br><br><a href='test.jsp'>返回</a>");
} else if (request.getParameter("act") != null
&& request.getParameter("act").equals("del")) {
XmlBean.DelXML(request);
out.println("<p align='center'><br><br>删除成功<br><br><a href='test.jsp'>返回</a>");
} else if (request.getParameter("act") != null
&& request.getParameter("act").equals("edit")) {
XmlBean.EditXML(request);
out.println("<p align='center'><br><br>修改成功<br><br><a href='test.jsp'>返回</a>");
} else {
out.print("<p align='center'><br><br>非法操作<br><br><a href='test.jsp'>返回</a>");
}
%>
/===============================正文结束========================================/