Use a JDOM to operate XML files

xiaoxiao2021-03-06  45

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 there is JDOM or Jaxb. The main founder Jason Hunter of JDOM in Javaone this year (2002) has a wonderful speech introduces Jdom Technology, the topic is Jdom Makes XML Easy. Get and install JDOM at http://jdom.org to download the latest version of JDOM. Take the 2 credit version of JDOM Beta8 as an example. After downloading, decompress the JAR file of JDOM is the file jdom.jar in the build directory, and will join the classpath. In addition, JDOM also requires support of those JAR files such as Xerces.jar, Jaxp.jar. If you appear in use: java.lang.nosuchmethoderror or java.lang.noclassdeffounderror: ORG / XML / SAX / SAXNOTRECognizedException You need to ensure that Xerces.jar files are located in other XML classes in ClassPath, such as JAXP or Crimson, these classes Files, including the previous versions of Xerces, may not support SAX2.0 or DOM Level 2. The above errors have so.

A simple example of JDOM has some similar to the DOM, but it is mainly implemented with SAX, you don't have to worry about processing speed and memory. In addition, there is almost no interface in JDOM, all of which are real class, and there is no class.

Here is an XML file for instances:

Java programming entry Zhang 3 Electronic Press < / Press> 35.0 2002-10-07 XML in Java Application </ Title> <author > 李 四 </ 作者> <Press> Hope Publishing House </ Press> <Price> 92.0 </ Price> <Publish Date> 2002-10-07 </ Publish Date> </ book> </ library></p> <p>Below is a bean: package XML; / *** 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 () {} / *** All information reading an 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 root element List books = root.getChildren (); // Get root elements All child elements Collection Element Element Book = NULL; XMLBean XML = NULL; for (INT i = 0; i <books.size (); i ) {xml = new xmlbean (); book = (element) books.get (i); // Get A book element XML.SetbookName (book.getchild ("book name") .getText ()); Xml.SetAuthor (Book.getChild ("author"); xml.setpub (book.getchild (" Publite ") .Gettext ()); Xml.SetPrice (Book.getChild (" price "); xml.setpubdate (Book.getChild (" Publish Date) .getText ()); xmlvector.add (XML);}}} catch (exception e) {system.err.println (E "error");} finally {Try {FI.Close ();</p> <p>} Catch (Exception e) {e.printStackTrace ();}} return xmlVector;} / *** delete XML file designation information * / public static void DelXML (HttpServletRequest request) throws Exception {FileInputStream fi = null; FileOutputStream fo = null ; try {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 root element List books = root.getchildren (); // Get a collection of root elements All child elements Books.Remove (XMLID); // Delete sub-elements in the specified location string indent = ""; boolean newline = true; xmloutputter outp = new xmloutputter (Indent, NewLines, "GBK"); 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 designation information * / public static void AddXML (HttpServletRequest request) throws Exception {FileInputStream fi = null; FileOutputStream fo = null; try {String path = request.getParameter ( "path"); fi = new Filein PutStream (PATH); SAXBUILDER SB = New Saxbuilder (); Document Doc = Sb.Build (Fi); Element Root = Doc.GtrooteElement (); // Get root element List books = root.getchildren (); // Get root String bookname set of elements all subelements = 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 name); newname.settext (bookname); newbook .addContent (newname);</p> <p>Element newauthor = new Element ( "Author"); newauthor.setText (author); newbook.addContent (newauthor); Element newpub = new Element ( "Publishing"); 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); // increase child elements string indent = ""; Boolean newline = true; xmloutputter outp = new XMLOUTPUTTER (IND, NewLines, "GBK"); 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 XML file designation information * / public static void EditXML (HttpServletRequest request) throws Exception {FileInputStream fi = null; FileOutputStream fo = null; try {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); ELEM Ent root = doc.getrootElement (); // Get root element List books = root.getchildren (); // Get a collection of root elements All child elements 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 name)); newname.settext (bookname); // Modify the book name to the new title Element NewAuthor = BOOK.GETCHILD (" Author) NewAr.Settext (Author);</p> <p>Element newpub = book.getchild ("Press House"); NewPub.Settext (PUB); Element NewPrice = Book.getChild ("Price"); Newprice.Settext (Price); Element NewDate = Book.getChild ("Publish Date" ); newdate.setText (Pubdate); // Books.Set (xmlid, book); // Modify child element string indent = ""; boolean newlines = true; xmloutputter outp = new XMLOUTPUTTER (IND, NewLines, "GBK") 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 ();}}}}</p> <p>Here is the JSP file operating: <% @ page contentty = "text / html; charset = GBK"%> <% @ page language = "java" import = java.util. *, XML. * "%> <HTML > <head> <title> Read XML file information </ title> </ head> <body> <h3 align = "center"> jdom operation XML file </ h3> <p align = "center"> read XML All information in the 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> Publishing House </ TD> <TD align = "center" width = "92"> price </ td> <td align = "center" width = "92"> Publish date </ td> <td align = "center" width = "94"> operation </ td> </ tr> </ table> <% string path = application.getRealPath ("/ test / xml /") "testc.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 ( "Press: " xml.getpub () " <br> "); out.println (" Price: " Xml.getPrice () " <br> "); Out.Println (" Publish Date: " Xml.getPubdate () "<br> <br > "); * /%> <table border =" 1 "Cellpadding =" 0 "</p> <p>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="XMLOK.JSP TIACT=DEL&ID=word =%> & path = <% = PATH%>> Delete </A> </ TD> </ TD> </ table> <%}%> </ center> <form method = "post" action = "xmlok.jsp"> <p align = "center"> <input type = "radio" value = "add" check name = "ACT"> Add information <input type = "radio" value = "edit" name = "ACT"> Editing data number: <SELECT Size = "1" name = "id"> <% for (INT i = 0; i <xmlall.size (); i ) {%> <option value = "<% = i%>>"% = i 1%> article </ option> <%}%> </ select> <br> title: <input type = "text" name = "bookname" size = "20"> <br> OF: <input TYPE = "text" name = "author" size = "20"> <br> Press: <input type = "text" name = "pub" size = "20"> <br> Price: <input type =</p> <p>"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 by the previous file: <% @ page contentType =" text / html; charset = GBK "%> <% @ page language =" java "import =" xml. * "%> <% IF (Request.getParameter (" ACT ")! = Null && Request.GetParameter (" ACT "). Equals (" Add ")) {XmlBean.AddXML (request); out.println (" <p align = 'center'> <br> <br> successfully added <br> <br> <a href=''> return </a> ");} else if (Request.GetParameter (" ACT ")! = Null && Request.getParameter (" ACT "). Equals (" del ") {xmlbean.delxml (request); out.println (" <p align = 'center'> <br> <br> deleted successfully <br> <br> <a href=''> return </a> ");} else if (request.getParameter ("! act ") = null && request.getParameter ( "act") equals ( "edit")) {XmlBean.EditXML (request);. out.println ( "<p align = 'center'> <br> <br> successfully modified <br> < br> <a href=''> return </a> ");} else {out.print (" <p align = 'center'> <br> <br> illegal operation <br> <br> <a href = ''> Return </a> ");</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-76239.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="76239" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.032</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = '1AvyggcQi8Dp1tjHvWUOdyNp3dMGitABNExWtg9cK44aQFb9EntuEDEEihioRaCymHeG8kJ53X1kgbykvXPsRA_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>