xml

我最近在学习了一下xml的创建和解析
主要是用dom4j来完成

1 xml的创建是通过DocumentHelper 类来创建一个XML文档对象
如:Document document  = DocumentHelper.createDocument();
DocumentHelper这个类在dom4j包中
2 通过DocumentHelper类中的createElement()方法来 创建一个普通的节点
3 通过 创建的XML文档对象 设置根节点 setRootElement();
4 可以通过 setAttribute(String name String value);来为Element对象添加属性
5 通过addElement(String name);来为指定的节点添加子节点
这是一个例子 如下
JAVA servlet
package org.com.cn.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.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

public class PlacardServlet extends HttpServlet{

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String fileURL = request.getRealPath("/XML/placard.xml");//XML文件的路径
File file = new File(fileURL);//
String title = request.getParameter("title");//通过Request对象获取数据
String content = request.getParameter("content");//通过Request对象获取数据
Document document = null;
Element placard = null;
DateFormat df = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");
if(!file.exists()){
document = DocumentHelper.createDocument();//创建一个XML文档对象
placard = DocumentHelper.createElement("placard");//创建一个placard的普通节点
document.setRootElement(placard);//然后将placard的节点设置为根节点
placard.addAttribute("version","2.0");//为placard添加version属性
Element description = placard.addElement("description");//在placard根节点添加一个子节点为description
description.setText("公告栏");//为description节点set文本内容
Element createTime = placard.addElement("createTime");//在placard根节点添加一个子节点为createTime
createTime.setText("创建于"+df.format(new Date()));//为createTime节点set文本内容
}else{
//如果file存在的话就
SAXReader reader = new SAXReader();
try {
document = reader.read(new File(fileURL));
placard = document.getRootElement();
} catch (DocumentException 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("GBK");
try{
XMLWriter writer = new XMLWriter(new FileWriter(fileURL),format);
writer.write(document);
writer.close();
}catch(IOException e){
e.printStackTrace();
}
request.getRequestDispatcher("XML/placard.xml").forward(request, response);
}

}

web.xml:
<?xml version="1.0" encoding="GBK"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>xml</display-name>
  <filter>
  <filter-name>CharacterEncodingFilter</filter-name>
  <filter-class>org.com.cn.filter.CharacterEncodingFilter</filter-class>
  <init-param>
  <param-name>encoding</param-name>
  <param-value>GBK</param-value>
  </init-param>
  </filter>
  <filter-mapping>
  <filter-name>CharacterEncodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
  <dispatcher>REQUEST</dispatcher>
  <dispatcher>FORWARD</dispatcher>
  </filter-mapping>
  <servlet>
  <servlet-name>PlacardServlet</servlet-name>
  <servlet-class>org.com.cn.servlet.PlacardServlet</servlet-class>
  </servlet>
  <servlet-mapping>
<servlet-name>PlacardServlet</servlet-name> 
  <url-pattern>/PlacardServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

JSP代码:
<%--index.jsp  添加公告信息页面--%>
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>保存公告信息到XML文件</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">   
<link rel="stylesheet" type="text/css" href="CSS/style.css">
<script language="javascript">
function check(form){
if(form.title.value==""){
alert("请输入公告标题!");form.title.focus();return false;
}
if(form.content.value==""){
alert("请输入公告内容!");form.content.focus();return false;
}
}
</script>
  </head>
 
  <body>
<form name="form1" method="post" action="PlacardServlet" target="_blank" onSubmit="return check(this)">
  <table width="500" height="271" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
    <tr>
      <td width="90" height="23">&nbsp;</td>
      <td width="410">&nbsp;</td>
    </tr>
    <tr>
      <td colspan="2" align="center">·添加公告信息</td>
    </tr>
    <tr>
      <td height="28" align="center">公告标题:</td>
      <td><input name="title" type="text" id="title" size="52"></td>
    </tr>
    <tr>
      <td height="157" align="center">公告内容:</td>
      <td><textarea name="content" cols="50" rows="9" id="content"></textarea></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><input name="Submit" type="submit" class="btn_grey" value="保存">
      &nbsp;
      <input name="Submit2" type="reset" class="btn_grey" value="重置"></td>
    </tr>
  </table>
</form> 
  </body>
</html>

还一个过滤器 这个不是重点:
java 代码:
package org.com.cn.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class CharacterEncodingFilter implements Filter {
protected FilterConfig filterConfig;
protected String encoding;
@Override
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}

@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if(encoding!=null){
request.setCharacterEncoding("GBK");
response.setContentType("text/html; charset="+encoding);
}
chain.doFilter(request, response);
}

@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");

}

}
这个就是一个xml创建的过程
xml的创建并不复杂 主要是要了解xml的结构 从结构去剖析

你可能感兴趣的:(xml)