Original article: JDOM operating XML files
Address: http://www.jspcn.net/htmlnews/200120272.html
---------------------------------------------------------------------------
This article is good ~ The basic operations of JDOM are instantiated. However, due to the outdated JDOM versions used by the author at that time, some code compilation errors may occur! Chinese support is not good! Therefore, Pharaoh modified the program on the basis of the original author! The compilation error and Chinese garbled characters are closed. Published for your learning and use.
Test environment: jdom1.0, WebLogic 8.1sp2, Tomcat 5.0, and IE 6. 0
// ===================================================== Start of the body ==== =============================================/
Java + xml = JDOM!
This is the goal of the JDOM designer. If you have used annoying sax or Dom to process XML, you will know why JDOM or jaxb is required. At this year's (2002) javaone conference, Jason Hunter, the main founder of JDOM, gave a wonderful speech about JDOM, entitled JDOM makes XML easy.
Obtain and install JDOM
In the http://jdom.org, you can download the latest version of JDOM. ToJDOM 1.0Take the two-step version as an example. After downloading and decompressing, The jdom jar file is the JDOM. jar file under the build Directory, which is added to the class path. In addition, JDOM also requires support for jar files such as xerces. jar and JAXP. jar in the lib directory. If the following error occurs during use:
Java. Lang. nosuchmethoderror
Or
Java. Lang. noclassdeffounderror: ORG/XML/sax/saxnotrecognizedexception
You need to ensure xerces. jar files are located in other XML classes such as JAXP or crimson in classpath. These class files, including older versions of xerces, may not support sax2.0 or DOM Level 2. As a result, the above error occurs.
A simple example
The JDOM processing method is similar to Dom, but it is mainly implemented using sax, so you don't have to worry about processing speed and memory. In addition, there are almost no interfaces in JDOM, and all the classes are real classes without class factory classes.
The following is the XML file used by the instance:Myxml. xml
<? XML version = "1.0" encoding = "UTF-8"?>
<Library>
<Book>
<Title> getting started with Java programming </title>
<Author> Zhang San </author>
<PRESS> electronic publishing house </PRESS>
<Price> 35.0 </price>
<Publication date> 2002-10-07 </publication date>
</Book>
<Book>
<Title> application of XML in Java </title>
<Author> Li Si </author>
<PRESS> hope press </PRESS>
<Price> 92.0 </price>
<Publication date> 2002-10-07 </publication date>
</Book>
</Library>
Below is the bean for operating the XML file:Xmlbean. Java
Package JDOM. test;
/**
* XML read/write 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 XML file information
*/
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 (); // obtain the root element.
List books = root. getchildren (); // obtain the set 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 ("name"). gettext ());
XML. setauthor (book. getchild ("author"). gettext ());
XML. setpub (book. getchild ("Press"). 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 specified information of an XML file
*/
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 (); // obtain the root element.
List books = root. getchildren (); // obtain the set 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. 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 specified XML file 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 (); // obtain the root element.
List books = root. getchildren (); // obtain the set 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 ("name ");
Newname. settext (bookname );
Newbook. addcontent (newname );
Element newauthor = new element ("author ");
Newauthor. settext (author );
Newbook. addcontent (newauthor );
Element newpub = new element ("publisher ");
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 sub-elements
// String indent = "";
// Boolean newlines = true;
// Xmloutputter outp = new xmloutputter (indent, newlines, "GBK ");
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 the specified information of an XML file
*/
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 (); // obtain the root element.
List books = root. getchildren (); // obtain the set 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 ("name ");
Newname. settext (bookname); // modify the name of a new book
Element newauthor = book. getchild ("author ");
Newauthor. settext (author );
Element newpub = book. getchild ("Press ");
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 the child element
// String indent = "";
// Boolean newlines = true;
// Xmloutputter outp = new xmloutputter (indent, newlines, "GBK ");
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 the operation:Test. jsp
<% @ Page contenttype = "text/html; charset = GBK" %>
<% @ Page Language = "Java" Import = "Java. util. *, JDOM. Test. *" %>
<HTML>
<Head>
<Title> Read XML files </title>
</Head>
<Body>
<H3 align = "center"> jdom xml file operations <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"> title </TD>
<TD align = "center" width = "92"> author </TD>
<TD align = "center" width = "92"> press </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 ("name:" + XML. getbookname () + "<br> ");
Out. println ("Author:" + XML. getauthor () + "<br> ");
Out. println ("publisher:" + XML. getpub () + "<br> ");
Out. println ("Price:" + XML. getprice () + "<br> ");
Out. println ("publication date:" + XML. getpubdate () + "<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"> <
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 Materials
<Input type = "radio" value = "edit" name = "act"> edit data sequence: <select size = "1"
Name = "ID">
<% For (INT I = 0; I <xmlall. Size (); I ++) {%>
<Option value = "<% = I %>"> entry <% = I + 1%> </option>
<% }%>
</SELECT> <br>
Book name: <input type = "text" name = "bookname" size = "20"> <br>
Author: <input type = "text" name = "author" size = "20"> <br>
Press: <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 submitted in 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> added successfully <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> deletion successful <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> modification successful <br> <a href = 'test. JSP '> return </a> ");
} Else {
Out. print ("<p align = 'center'> <br> illegal operation <br> <a href = 'test. JSP '> return </a> ");
}
%>
/=================================== End of the body ======== ===========================================/
Note:
1,In the xmlbean. Java file, the pharaoh's note text is yellow, where it is modified, and the purple part leads to the original program!
2. The default encoding of the myxml. xml file is changed to the old one.Encoding = "UTF-8"The cause is that it is always abnormal to parse GBK or gb2312 under WebLogic 8. Tomcat is good. It may be because Weblogic's default XML parser does not support GBK, this problem has not been solved ~ If any expert knows how to solve the problem, please reply to this post and tell me ~~ Thank you!