1. 程式人生 > >dom4j建立XML文件

dom4j建立XML文件

下面用一個公告例項顯示dom4j的使用:將公告資訊儲存到xml檔案中。

index.jsp:用於收集公告資訊

<%@ page language="java" import="java.util.*"
	contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!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>起始頁</title>
</head>
<body>
	
	<form name="form1" method="post" action="PlacardServlet" target="_blank" onsubmit="return check(this)">
	   公告標題:<input name="title" type="text" id="title" size="52">
	   公告內容:<textarea name="content" cols="50" rows="9" id=content></textarea>
	 <input name="Submit" type="submit" class="btn_grey" value="儲存">
	 <input name="Submit2" type="reset" class="btn_grey" value="重置">
	</form>
</body>
</html>
PlacardServlet.java:
package com.home.web.servlet;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * Servlet implementation class PlacardServlet
 */
@WebServlet("/PlacardServlet")
public class PlacardServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PlacardServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        String fileUrl = request.getRealPath("/xml/placard.xml");
        File file = new File(fileUrl);
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        Document document = null;
        Element placard = null;
        DateFormat df = new SimpleDateFormat("yyyy 年 MM 月 dd 日 HH 時 mm 分");
        if (!file.exists()) {
            document = DocumentHelper.createDocument();
            placard = DocumentHelper.createElement("placard");
            document.setRootElement(placard);
            placard.addAttribute("version", "2.0");
            Element description = placard.addElement("description");
            description.setText("公告欄");
            Element createTime = placard.addElement("createTime");
            createTime.setText("創建於" + df.format(new Date()));
        } else {
            SAXReader reader = new SAXReader();
            try {
                document = reader.read(new File(fileUrl));
                placard = document.getRootElement();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        /********* 新增公告資訊 **********/
        String id = String.valueOf(placard.elements("info").size() + 1);
        Element info = placard.addElement("info");
        info.addAttribute("id", id);
        Element title_info = info.addElement("title");
        title_info.setText(title);
        Element content_item = info.addElement("content");
        content_item.addCDATA(content);
        Element pubDate_item = info.addElement("pubDate");
        df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        pubDate_item.setText(df.format(new Date()));

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        try {
            XMLWriter writer=new XMLWriter(new FileWriter(fileUrl), format);
            writer.write(document);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.getRequestDispatcher("xml/placard.xml").forward(request, response);
	}

}

注意要現在該例項根目錄下建立xml資料夾,不需要建立XML檔案

效果: