JSP簡單練習-使用JDOM建立xml檔案

來源:互聯網
上載者:User

標籤:使用jdom建立xml檔案   建立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檔案得到:



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.