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