DocumentHelper和SAXReader解析XML字符串

最近在看湖北中烟OA门户的项目,中烟门户里面解析XML文档使用的是DocumentHelper,之前做的智能导航项目里面解析XML使用的是SAXReader,很好奇它们有什么区别,于是就查资料将两者的用法简单总结了一下。

SAXReader用法示例

package com.eway.signature.action;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class UploadFile{

    private static Log logger = LogFactory.getLog(UploadFile.class);
    //要上传的配置文件的路径
    static String uploadCfgFile = "WEB-INF/conf/uploadfile.xml";
    Document uploadDocument;//文档对象实体
    Map uploadMap = new HashMap();

    /** * 获取配置文件的绝对路径 * @param request * @return */
    private String getUploadCfgFilePath(ServletRequest request){
        return ((HttpServletRequest) request).getSession().getServletContext().getRealPath("uploadCfgFile");
    }

    /** * 初始化配置文件 * @param request * @return */
    private Document initUploadCfgDocument(ServletRequest request){
        SAXReader saxReader = new SAXReader();
        try {
            //得到指定文件,以流的形式对文件进行序列化
            FileInputStream fis = new FileInputStream(getUploadCfgFilePath(request));
            uploadDocument = (Document) saxReader.read(fis);
        } catch (FileNotFoundException e) {
            logger.debug(e);
        } catch (DocumentException e) {
            logger.debug(e);
        }
        return uploadDocument;
    }

    /** * 获取配置文件 * @param request * @return */
    private Document getUploadCfgDocument(ServletRequest request){
        if (this.uploadDocument == null) {
            this.uploadDocument = initUploadCfgDocument(request);
        }
        return this.uploadDocument;
    }

    /** * 获取某个指定ticket节点的配置属性 * @param request * @return */
    private Map getUploadMap(ServletRequest request){

        Document uploadDocument = getUploadCfgDocument(request);
        //得到XML的根节点(message)
        Element root = uploadDocument.getRootElement();
        Iterator tickets = root.element("body").element("ticketNotify").elementIterator();
        //获取ticketNotify节点下所有的ticket节点的配置属性,并将其放到Map中
        while (tickets.hasNext()) {
            Element ticket = (Element) tickets.next();
            uploadMap.put("id", ticket.attributeValue("id"));
            uploadMap.put("dealTime", ticket.attributeValue("dealTime"));
            uploadMap.put("status", ticket.attributeValue("status"));
        }
        //Element.asXML方法,获得包括该标签的所有XML数据
// System.out.println(root.element("body").asXML());
        return uploadMap;
    }
}

DocumentHelper的用法示例

package com.eway.signature.action;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class UploadFile{

    private static Log logger = LogFactory.getLog(UploadFile.class);
    //要上传的配置文件的路径
    static String uploadCfgFile = "WEB-INF/conf/uploadfile.xml";
    Document uploadDocument;//文档对象实体
    Map uploadMap = new HashMap();

    /** * 获取配置文件的绝对路径 * @param request * @return */
    private String getUploadCfgFilePath(ServletRequest request){
        return ((HttpServletRequest) request).getSession().getServletContext().getRealPath("uploadCfgFile");
    }

    /** * 获取配置文件 * @param request * @return */
    private Document getUploadCfgDocument(ServletRequest request){

        String sText;
        StringBuffer sb = new StringBuffer();
        try {
            //得到指定文件,以流的形式对文件进行序列化
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(new FileInputStream(getUploadCfgFilePath(request))));
            for (;;) {
                sText = br.readLine();//一行一行的读取数据
                if(sText == null){
                    break;
                }
                sb.append(sText);
            }
            uploadDocument = DocumentHelper.parseText(sb.toString());
        } catch (FileNotFoundException e) {
            logger.debug(e);
        } catch (DocumentException e) {
            logger.debug(e);
        } catch (IOException e) {
            logger.debug(e);
        }
        return uploadDocument;
    }

    /** * 获取某个指定ticket节点的配置属性 * @param request * @return */
    private Map getUploadMap(ServletRequest request){

        Document document = getUploadCfgDocument(request);
        //获取根节点
        Element root = document.getRootElement();
        Iterator tickets = root.element("body").element("ticketNotify").elementIterator();
        //获取ticketNotify节点下所有的ticket节点的配置属性,并将其放到Map中
        while (tickets.hasNext()) {
            Element ticket = (Element) tickets.next();
            uploadMap.put("id", ticket.attributeValue("id"));
            uploadMap.put("dealTime", ticket.attributeValue("dealTime"));
            uploadMap.put("status", ticket.attributeValue("status"));
        }
        //Element.asXML方法,获得包括该标签的所有XML数据
// System.out.println(root.element("body").asXML());
        return uploadMap;
    }

}

更多使用请参看DocumentHelper的在线API:

http://dom4j.sourceforge.net/dom4j-1.6.1/apidocs/org/dom4j/DocumentHelper.html#createAttribute%28org.dom4j.Element,%20org.dom4j.QName,%20java.lang.String%29

SAXReader可以直接使用read()方法将一个文件输入流转换成Document对象;而DocumentHelper不能直接操作文件输入流,只能使用parseText()方法将string字符串解析成Document对象,所以必须先将文件输入流写到String字符串中,再由DocumentHelper去解析。

更多使用继续发现中~

你可能感兴趣的:(IO,SAXReader,解析xml,DocumentHe)