Jdom operation XML file (Pharaoh revised version)

Source: Internet
Author: User
Tags add date format gettext integer string version xml parser
Dom|xml

Original: jdom operation XML File
Address: http://www.jspcn.net/htmlnews/200120272.html
---------------------------------------------------------------------------
This article is good ~ to jdom the basic operation of the instantiation, but because the author used the Jdom version is still relatively old, so some code will compile error! It's not good to support Chinese! Therefore, the pharaoh on the basis of the original author of the program made changes! Hugh is getting the problem of compiling errors and Chinese garbled characters. Published for everyone to learn and use.
Test environment: Jdom1.0,weblogic 8.1sp2,tomcat 5.0,ie 6. 0
/================================== Body Start =======================================/
Java + XML = JDOM!
This is the goal of Jdom designers. If you've ever used annoying sax or DOM to process XML, you'll know why you have Jdom or JAXB. At the JavaOne meeting this year (2002), Jdom's main founder, Jason Hunter, had an excellent presentation on jdom technology, which was jdom makes XML easy.

Get and install Jdom

The latest version of Jdom can be downloaded at http://jdom.org. Take the 2 version of Jdom 1.0 as an example. After downloading, the Jdom jar file is the file Jdom.jar of the build directory and joins the CLASSPATH. In addition, Jdom also needs the support of those jar files such as Xerces.jar,jaxp.jar in the Lib directory. If you receive the following error in use:
Java.lang.NoSuchMethodError or Java.lang.noclassdeffounderror:org/xml/sax/saxnotrecognizedexception You need to ensure that Xerces.jar files in Classpath are located in other XML classes, such as JAXP or crimson, these class files, including previous versions of Xerces, may not support SAX2.0 or DOM level 2. This leads to the above error.

A simple example

Jdom is somewhat similar to DOM, but it is mainly implemented with sax, and you don't have to worry about handling speed and memory problems. In addition, there are almost no interfaces in the Jdom, the classes are all real classes, no class factory class.

The following is an XML file for the instance: Myxml.xml

<?xml version= "1.0" encoding= "Utf-8"?>
< stacks >
< book >
< title >java Programming Primer </title >
< author > John </author >
< publishing house > Electronic publishing House </publishing house >
< price >35.0</price >
< published date >2002-10-07</publication date >
</book >
< book >
< title >xml application in Java </title >
< author > Dick </author >
< publishing house > Hope Publishing House </publishing house >
< price >92.0</price >
< published date >2002-10-07</publication date >
</book >
</Stacks >

Here is the Bean:XmlBean.java to manipulate the XML file

Package jdom.test;

/**
* Read-write operations bean for XML
*/
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 of 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 (); Gets 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 ("title"). 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 specify 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 (); Gets the collection of all child elements of the root element
Books.remove (xmlid);//delete child elements at specified location
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 to specify 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 (); Gets 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 (); Gets 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 ("title");
Newname.settext (bookname)//Change the title to the 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 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 ();
}
}
}
}

Here is the JSP file for the operation: test.jsp

<%@ page contenttype= "TEXT/HTML;CHARSET=GBK"%>
<%@ page language= "java" import= "java.util.*,jdom.test.*"%>
<title> read XML file Data </title>
<body>

<p align= "center" > read all the data in the XML file </p>
<center>
<table border= "1" cellpadding= "0" cellspacing= "1"
Style= "Border-collapse:collapse" width= "80%" id= "AutoNumber1" >
<tr>
&LT;TD align= "center" width= "a" > title </td>
&LT;TD align= "center" width= "a" > author </td>
&LT;TD align= "center" width= "> Publishing house </td>
&LT;TD align= "center" width= "> Price </td>
&LT;TD align= "center" width= "a" > Publication date </td>
&LT;TD align= "center" width= "> 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 ("title:" +xml.getbookname () + "<br>");
Out.println ("Author:" +xml.getauthor () + "<br>");
Out.println ("Publishing House:" +xml.getpub () + "<br>");
Out.println ("Price:" +xml.getprice () + "<br>");
Out.println ("Published Date:" +xml.getpubdate () + "<br><br>");
*/
%>
<table border= "1" cellpadding= "0" cellspacing= "1"
Style= "Border-collapse:collapse" width= "80%" id= "AutoNumber2" >
<tr>
&LT;TD align= "center" width= "><%=xml.getbookname" ()%></td>
&LT;TD align= "center" width= "><%=xml.getauthor" ()%></td>
&LT;TD align= "center" width= "><%=xml.getpub" ()%></td>
&LT;TD align= "center" width= "><%=xml.getprice" ()%></td>
&LT;TD align= "center" width= "><%=xml.getpubdate" ()%></td>
&LT;TD align= "center" width= "><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 material
<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%>" > <%=i + 1%> Strip </option>
<%}%>
</select><br>
Title: <input type= "text" name= "BookName" size= "><br>"
Author: <input type= "text" name= "author" size= "><br>"
Publisher: <input type= "text" Name= "pub" size= "><br>"
Price: <input type= "text" name= "Prices" size= "><br>"
Date: <input type= "text" name= "pubdate" size= "></p>"
<input type= "hidden" name= "path" value= "<%=path%>" >
<p align= "center" ><input type= "Submit" value= "submitted" name= "B1" ><input
Type= "reset" value= "reset" name= "B2" ></p>
</form>
</body>

The following is a JSP file that processes the previous file submission: 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> Add success <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 success <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> modified successfully <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 > ");
}
%>
/=============================== Body End ========================================/

Note:

1,xmlbean.java file in the name of the Pharaoh note the yellow part, is the change of place, the purple is the part of the original program written!

Default encoding for 2,myxml.xml files The reason that Pharaoh changed to encoding= "Utf-8" is that it's always unusual to parse GBK or GB2312 under WebLogic 8, and Tomcat is good, May be WebLogic own default XML parser does not support GBK bar, this problem has not been well ~ If any master know how to solve, please reply to this post tell me ~ ~ Thank you!



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.