Java 服务端动态生成XML文件
?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome to VP!</title>
</head>
<body>
<form name="User" method="post" action="createXml.do" accept-charset="utf-8">
??????????? 姓名:<input type="text" name="name" />
??????????? <br/>
??????????? <br/>
??????????? 手机:<input type="text" name="tel" />
??????????? <br/>
??????????? <br/>
??????????? <input type="submit" value="Join" />
??????? </form>
</html>
再次是servlet源码(CreateXml.java):
public class CreateXml extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
?? // TODO Auto-generated method stub
?? doPost(request,response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
?? // TODO Auto-generated method stub
?? String name=request.getParameter("name");
?? byte[] Bname=name.getBytes("ISO-8859-1");
?? name=new String(Bname);
??
?? String tel=request.getParameter("tel");
??
??
??JavaToXml XML=new JavaToXml();
?? try {
??? XML.BuildXMLDoc(name, tel);
?? } catch (JDOMException e) {
??? // TODO Auto-generated catch block
??? e.printStackTrace();
?? }
?? response.sendRedirect("index.jsp");
}
}
最后是JavaToXml .java源码(你需要一个jar包:jdom.jar):
public class JavaToXml {
public void BuildXMLDoc(String name, String tel) throws IOException,
??? JDOMException {
?? // 创建根节点 list;
?? Element root = new Element("List");
?? // 根节点添加到文档中;
?? Document Doc = new Document(root);
?? // 创建节点 user;
?? Element elements = new Element("User");
?? // get the current time
?? SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
?? Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
?? String xmlName = formatter.format(curDate);
?? // 给 user 节点添加属性 id;
?? elements.setAttribute("id", xmlName);
?? // 给 user 节点添加子节点并赋值;
?? // new Element("name")中的 "name" 替换成表中相应字段,setText("xuehui")中 "xuehui
?? // 替换成表中记录值;
?? elements.addContent(new Element("Name").setText(name));
?? elements.addContent(new Element("Tel").setText(tel));
?? //System.out.println(name + "---" + tel);
?? // 给父节点list添加user子节点;
?? root.addContent(elements);
?? XMLOutputter XMLOut = new XMLOutputter();
?? // 输出 user.xml 文件;
?? XMLOut.output(Doc, new FileOutputStream("D:/"+xmlName + ".xml"));
}
}