當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JSP简单练习-使用JDOM创建xml文件
生活随笔
收集整理的這篇文章主要介紹了
JSP简单练习-使用JDOM创建xml文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
注意:在編寫代碼前,請確保該Web目錄下的"WEB-INF/lib"下包含jdom.jar包!
<%@ page language="java" contentType="text/html; charset=gb2312" %> <%@ page import="org.jdom.*, org.jdom.output.*, java.io.IOException, java.io.FileWriter" %> <html> <body><%// 所有的XML元素都是Element的實例,根元素也不例外Element rootElement=new Element("users");// 以根元素作為參數創建Document對象。一個Document只有一個根,即root元素。Document myDocument=new Document(rootElement);Element userElement=new Element("user"); //創建user元素rootElement.addContent(userElement); // 將user元素作為content添加到根元素Element idElement=new Element("id"); // 創建id元素idElement.addContent("1"); // 將1作為Content添加到idElement// 將idElement元素作為content添加到userElement元素userElement.addContent(idElement);// 其他元素的操作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("張三");userElement.addContent(true_nameElement);Element ageElement=new Element("age");ageElement.addContent("26");userElement.addContent(ageElement);Element sexElement=new Element("sex");sexElement.addContent("男");userElement.addContent(sexElement);// 給ageElement元素創建名為ageunit的屬性,值為"歲"ageElement.setAttribute(new Attribute("ageunit","歲"));// 輸出到控制臺Format format=Format.getPrettyFormat();format.setEncoding("gb2312"); // 設置解碼方式XMLOutputter xmlOut=new XMLOutputter(format);try{xmlOut.output(myDocument, System.out);}catch(IOException e){e.printStackTrace();}// 輸出到XML文件FileWriter writer=new FileWriter("E:/myeclipseProgram/jspdemo/WebRoot/WEB-INF/user.xml");xmlOut.output(myDocument,writer);writer.close();%> </body> </html>打開xml文件得到:
總結
以上是生活随笔為你收集整理的JSP简单练习-使用JDOM创建xml文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2019 Java 开发者跳槽指南.pd
- 下一篇: 女神节快乐!世界上第一位程序员就是女神