This article is good ~ it instantiates the basic operations of JDOM. However, because the JDOM version used by the author at that time was still relatively old, some codes will compile incorrectly! Supporting Chinese is not good either! Therefore, Pharaoh made modifications to the program based on the original author's work! Fixed compilation errors and garbled Chinese characters. Publish it for everyone to learn and use.
Test environment: jdom1.0, weblogic 8.1sp2, tomcat 5.0, IE 6.0
/==================================Text begins============== ==========================/
Java + XML = JDOM!
This is the goal of JDOM designers. If you have ever used the annoying SAX or DOM to process XML, you will know why JDOM or JAXB is needed. At this year's (2002) JavaOne conference, Jason Hunter, the main founder of JDOM, gave a wonderful speech introducing JDOM technology, titled JDOM Makes XML Easy.
Obtain and install JDOM
The latest version of JDOM can be downloaded at http://jdom.org . Take the binary version of JDOM 1.0 as an example. After downloading, unzip it. The JDOM jar file is the file jdom.jar in the build directory and add it to the class path. In addition, JDOM also needs the support of those jar files in the lib directory such as xerces.jar and jaxp.jar. If the following error occurs during use:
java.lang.NoSuchMethodError
or
java.lang.NoClassDefFoundError: org/xml/sax/SAXNotRecognizedException
You need to ensure that the xerces.jar file is located before other XML classes, such as JAXP or Crimson, in the CLASSPATH. These class files, including previous older versions of xerces, may not support SAX2.0 or DOM Level 2. This resulted in the above error.
a simple example
The processing method of JDOM is somewhat similar to DOM, but it is mainly implemented using SAX, so you don't have to worry about processing speed and memory issues. In addition, there are almost no interfaces in JDOM, all classes are real classes, and there are no class factory classes.
The following is the XML file used for the example: MyXml.xml
<?xml version="1.0" encoding="utf-8"?>
<Library>
<book>
<Book title>Introduction to Java Programming</Book title>
<Author>Zhang San</Author>
<Publishing House>Electronic Publishing House</Publishing House>
<Price>35.0</Price>
<Publication date>2002-10-07</Publication date>
</book>
<book>
<Book title>Application of XML in Java</Book title>
<Author>Li Si</Author>
<Publishing House>Hope Publishing House</Publishing House>
<Price>92.0</Price>
<Publication date>2002-10-07</Publication date>
</book>
</library>
The following are Beans that operate XML files: XmlBean.java
package jdom.test;
/**
* XML read and write operation 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() {
}
/**
* Read all information from XML file
*/
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(); // Get the root element
List books = root.getChildren(); // Get the collection of all child elements of the root element
Element book = null;
XmlBean xml = null;
for (int i = 0; i < books.size(); i++) {
xml = new XmlBean();
book = (Element) books.get(i); // Get the first book element
xml.setbookname(book.getChild("Book Name").getText());
xml.setauthor(book.getChild("Author").getText());
xml.setpub(book.getChild("Publishing House").getText());
xml.setprice(book.getChild("price").getText());
xml.setpubdate(book.getChild("Publication Date").getText());
xmlVector.add(xml);
}
} catch (Exception e) {
System.err.println(e + "error");
} finally {
try {
fi.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return xmlVector;
}
/**
* Delete XML file specified information
*/
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(); // Get the root element
List books = root.getChildren(); // Get the collection of all child elements of the root element
books.remove(xmlid);//Delete the child element at the specified position
// 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();
}
}
}
/**
* Add XML file specification information
*/
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(); // Get the root element
List books = root.getChildren(); // Get the collection of all child elements of the root element
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("book");
Element newname = new Element("Book Title");
newname.setText(bookname);
newbook.addContent(newname);
Element newauthor = new Element("author");
newauthor.setText(author);
newbook.addContent(newauthor);
Element newpub = new Element("Publishing House");
newpub.setText(pub);
newbook.addContent(newpub);
Element newprice = new Element("price");
newprice.setText(price);
newbook.addContent(newprice);
Element newdate = new Element("Publication date");
newdate.setText(pubdate);
newbook.addContent(newdate);
books.add(newbook);//Add child elements
// 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();
}
}
}
/**
* Modify XML file specified information
*/
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(); // Get the root element
List books = root.getChildren(); // Get the collection of all child elements of the root element
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("Book Title");
newname.setText(bookname);//Modify the book name to a new title
Element newauthor = book.getChild("Author");
newauthor.setText(author);
Element newpub = book.getChild("Publishing House");
newpub.setText(pub);
Element newprice = book.getChild("price");
newprice.setText(price);
Element newdate = book.getChild("Publication Date");
newdate.setText(pubdate);
//books.set(xmlid,book);//Modify sub-elements
// 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();
}
}
}
}
The following is the jsp file for operation: test.jsp
<%@ page contentType="text/html;charset=GBK"%>
<%@ page language="java" import="java.util.*,jdom.test.*"%>
<html>
<head>
<title>Read XML file data</title>
</head>
<body>
<h3 align="center">JDOM operation XML file</h3>
<p align="center">Read all data in the XML file</p>
<center>
<table border="1" cellpadding="0" cellspacing="1"
style="border-collapse: collapse" width="80%" id="AutoNumber1">
<tr>
<td align="center" width="92">Book title</td>
<td align="center" width="92">Author</td>
<td align="center" width="92">Publisher</td>
<td align="center" width="92">Price</td>
<td align="center" width="92">Publication date</td>
<td align="center" width="94">Operation</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("Book name:"+xml.getbookname()+"<br>");
out.println("Author:"+xml.getauthor()+"<br>");
out.println("Publishing House:"+xml.getpub()+"<br>");
out.println("Price:"+xml.getprice()+"<br>");
out.println("Publication date:"+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%>">Delete</a></td>
</tr>
</table>
<%}%></center>
<form method="POST" action="xmlaction.jsp">
<p align="center"><input type="radio" value="add" checked name="act">Add information
<input type="radio" value="edit" name="act">Edit data serial number:<select size="1"
name="id">
<%for (int i = 0; i < xmlall.size(); i++) {%>
<option value="<%=i%>">Article <%=i + 1%></option>
<%}%>
</select><br>
Book title:<input type="text" name="bookname" size="20"><br>
Author:<input type="text" name="author" size="20"><br>
Publisher:<input type="text" name="pub" size="20"><br>
Price:<input type="text" name="price" size="20"><br>
Date:<input type="text" name="pubdate" size="20"></p>
<input type="hidden" name="path" value="<%=path%>">
<p align="center"><input type="submit" value="Submit" name="B1"><input
type="reset" value="Reset" name="B2"></p>
</form>
</body>
</html>
The following is the jsp file that handles the submission of the previous file: 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>Added successfully<br><br><a href='test.jsp'>Return</a>");
} else if (request.getParameter("act") != null
&& request.getParameter("act").equals("del")) {
XmlBean.DelXML(request);
out.println("<p align='center'><br><br>Delete successfully<br><br><a href='test.jsp'>Return</a>");
} else if (request.getParameter("act") != null
&& request.getParameter("act").equals("edit")) {
XmlBean.EditXML(request);
out.println("<p align='center'><br><br>Modification successful<br><br><a href='test.jsp'>Return</a>");
} else {
out.print("<p align='center'><br><br>Illegal operation<br><br><a href='test.jsp'>Return</a>");
}
%>
/================================End of text================ ========================/
Remark:
1. The yellow part of the Pharaoh's name text in the XmlBean.java file is the modification, and the purple part is the writing method of the original program!
2. The default encoding of the MyXml.xml file has been changed to encoding="utf-8" because it is always abnormal when parsing GBK or GB2312 under weblogic 8. Tomcat is fine, and it may be weblogic's own default xml. The parser does not support GBK. This problem has not been solved. If any expert knows the solution, please reply to this post and tell me~~ Thank you everyone!