Simple JSP exercise-use JDOM to create xml files
Note: before writing code, make sure that the "WEB-INF/lib" under the Web directory contains the jdom. jar package!
<% @ Page language = "java" contentType = "text/html; charset = gb2312" %> <% @ page import = "org. jdom. *, org. jdom. output. *, java. io. IOException, java. io. fileWriter "%><% // All XML elements are Element instances, and the root Element is no exception. Element rootElement = new Element ("users"); // create a Document object with the root Element as the parameter. A Document has only one root, that is, the root element. Document myDocument = new Document (rootElement); Element userElement = new Element ("user"); // create the user Element rootElement. addContent (userElement); // Add the user Element as the content to the root Element idElement = new Element ("id"); // create the id Element idElement. addContent ("1"); // Add 1 to idElement as Content // Add idElement as content to userElement. addContent (idElement); // operation of other elements Element nameElement = new Element ("name"); nameElement. addContent ("zs"); userElement. addContent (nameElement); Element passwordElement = new Element ("password"); passwordElement. addContent ("123456"); userElement. addContent (passwordElement); Element true_nameElement = new Element ("true_name"); true_nameElement.addContent ("zhangsan"); userElement. addContent (true_nameElement); Element ageElement = new Element ("age"); ageElement. addContent ("26"); userElement. addContent (ageElement); Element sexElement = new Element ("sex"); sexElement. addContent ("male"); userElement. addContent (sexElement); // create an attribute named ageunit for the ageElement. The value is "Age" ageElement. setAttribute (new Attribute ("ageunit", ""); // output to the console Format format = Format. getPrettyFormat (); format. setEncoding ("gb2312"); // sets the decoding method XMLOutputter xmlOut = new XMLOutputter (format); try {xmlOut. output (myDocument, System. out);} catch (IOException e) {e. printStackTrace ();} // output to XML file FileWriter writer = new FileWriter ("E:/myeclipseProgram/jspdemo/WebRoot/WEB-INF/user. xml "); xmlOut. output (myDocument, writer); writer. close (); %>
Open the xml file and get: