您的位置:首页 > Web前端 > JavaScript

JSP简单练习-使用JDOM创建xml文件

2015-02-01 18:30 357 查看
注意:在编写代码前,请确保该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文件得到:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: