一个用DOM4J来读取XML的工具类

/*
 * XmlHandle.java
 * Created on 2005-1-14
 * Copyright (c) jobcn.com. All rights reserved.
 */

package com.util;

import java.io.File;
import java.io.FileWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;
import org.dom4j.io.HTMLWriter;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 处理 XML 的工具. <p/>
 *
 * <pre>
 *        这个工具类是用于处理 XML . XML 的数据格式应该如下:
 *        &lt;?xml version=&quot;1.0&quot; encoding=&quot;gbk&quot;?&gt;
 *        &lt;root&gt;
 *        &lt;field id=&quot;int&quot; name=&quot;string&quot; email=&quot;string&quot; comment=&quot;text&quot; /&gt;
 *        &lt;documentAttribute maxIid=&quot;2&quot; /&gt;
 *        &lt;row id=&quot;1&quot; name=&quot;jacky&quot; email=&quot;jacky@domain.com&quot; comment=&quot;文本&quot;/&gt;
 *        &lt;row id=&quot;2&quot; name=&quot;lily&quot; email=&quot;lily@domain.com&quot;&gt;
 *         &lt;comment&gt;
 *             &lt;![CDATA[文本1 文本2]]&gt;
 *         &lt;/comment&gt;
 *        &lt;/row&gt;
 *        &lt;/root&gt;
 * </pre>
 *
 * <br/>
 *
 * @author Loist Loh
 * @version 1.0
 */
public class XmlHandle
{
    private static XmlHandle instance = new XmlHandle();

    /**
     * 构造函数
     */
    public XmlHandle()
    {
    }

    /**
     * 程序入口.
     *
     * @param args
     */
    public static void main(String[] args)
    {
        XmlHandle xmlHandle = new XmlHandle();
        try
        {
            // URL url = new URL("file", null, System.getProperty("user.dir") + File.separator + "xml/test.xml");
            Document document = null;
            document = xmlHandle.getXmlFromFile("conf/a.xml");
            String str = xmlHandle.getUniqueNodeDataFromXml(document,"/conf/action/im/mail","mail_host");
            boolean flag = xmlHandle.setSingleXmlData(document, "/conf/action/im/mail", "mail_host", "192.168.60.131", false);
           // xmlHandle.saveXmlToFile("conf/a.xml", document);
            System.out.println(str);

            System.out.println("程序结束!");
        } catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }

    /*<conf>
     * <action class="backupsubsystem.cticlient.Jobcn_Cti_SnapShot_TelLog2"></action>
     <action class="backupsubsystem.testclient.Test" ></action>
     <action class="backupsubsystem.openfire.OpenFire_Admin"></action>
     *</conf>
     * 获取指定节点某个属性的值,返回的是一个LIST,例如:document = xmlHandle.getXmlFromFile("conf\\alarm-config.xml");
   List<String> list = xmlHandle.getDataFromXml(document, "/conf",
     "action","class");
     *获取conf/action  节点属性为class的所有值
     *返回:一个包含backupsubsystem.cticlient.Jobcn_Cti_SnapShot_TelLog2,backupsubsystem.testclient.Test,backupsubsystem.openfire.OpenFire_Admin的List
     */
   
    public List<String> getDataFromXml(Document document,String strCondition,String key,String attribute)
    {
      List<String> list = new ArrayList<String>();
         Node root = document.selectSingleNode(strCondition);  
         if (root != null)
         {
          List nodeslist = root.selectNodes(key);  
             for(Object o:nodeslist){  
                 Element e = (Element) o;  
                 String className=e.attributeValue(attribute);     
                 list.add(className);
             }
         }
     return list;
    }
    /*<conf>
     *  <action class="backupsubsystem.cticlient.Jobcn_Cti_SnapShot_TelLog2">
         <mail_host>192.168.60.131</mail_host>
         <mail_user>JCNEP3160</mail_user>
         <mail_pwd>820815</mail_pwd>
         <mail_from>tuping@jobcn.com</mail_from>
         <mail_to>tuping@jobcn.com</mail_to>
     </action>
     * </conf>
     * 获取单个节点的值,例如:String str = xmlHandle.getUniqueNodeDataFromXml(document,"/conf/action","mail_to");
     * 就是去取/conf/action 下面的mail_to节点的值
     *
     * 返回tuping@jobcn.com
     */
    public String getUniqueNodeDataFromXml(Document document,String strCondition,String key)
    {
      String nodeText = "";
         Node root = document.selectSingleNode(strCondition);  
         if (root != null)
         {
          List nodeslist = root.selectNodes(key);
          if(nodeslist.size()!=1)
          {
           nodeText="";
          }
          else
          {
           nodeText = ((Element)nodeslist.get(0)).getText();
          }
           
         }
     return nodeText;
    }
   
    public List<String> getUniqueNodeDataFromXml2(Document document,String strCondition,String key)
    {
      List<String> list = new ArrayList<String>();
         Node root = document.selectSingleNode(strCondition);  
         if (root != null)
         {
          List nodeslist = root.selectNodes(key);
          if(nodeslist.size()>1)
          {
          
          }
             for(Object o:nodeslist){  
                 Element e = (Element) o;  
                 //String className=e.attributeValue("class");     
                 list.add(e.getText());
             }
         }
     return list;
    }
   
    /**
     * 获得一个本类的单一实例. com.jobcn.util.XmlHandle = XmlHandle.getInstance();
     *
     * @return com.jobcn.util.XmlHandle
     */
    public static XmlHandle getInstance()
    {
        return instance;
        // return new XmlHandle();
    }

    /**
     * 从本地磁盘读取一个 xml 文件, 返回一个 Document, 如果返回结果为 null 表示读取失败.
     *
     * @param strFilePath
     *            文件的路径. 可以是相对路径也可以是绝对路径.
     * @return document
     */
    public Document getXmlFromFile(String strFilePath)
    {
        Document theResult = null;
        theResult = getXmlFromFile(new File(strFilePath));
        return theResult;
    }
   
    public Document getXmlFromFile(File file)
    {
        Document theResult = null;
        try
        {
            SAXReader reader = new SAXReader();
            Document document = reader.read(file);
            theResult = document;
        } catch (Exception e)
        {
         e.printStackTrace();
         System.out.println(file.getAbsolutePath() + "文件读取出错!");
        }
        return theResult;
    }

    /**
     * 从URL读取一个 xml 文件, 返回一个 Document, 如果返回结果为 null 表示读取失败.
     *
     * @param url
     *            xml 文件的 java.net.URL 的实例.
     * @return document
     */
    public Document getXmlFromUrl(URL url)
    {
        Document theResult = null;
        try
        {
            SAXReader reader = new SAXReader();
            Document document = reader.read(url.openStream());
            theResult = document;
        } catch (Exception e)
        {
        }
        return theResult;
    }

    /**
     * 用于保存 document 到 xml 格式的文本文件. 返回结果若为 true 表示文件保存成功, 否则失败. xml 的字符编码为 gbk
     *
     * @param strFilePath
     *            保存路径.
     * @param document
     *            要保存的XML文档
     * @return boolean 执行结果, true 为成功;false 为失败.
     */
    public boolean saveXmlToFile(String strFilePath, Document document)
    {
        boolean theResult = false;
        try
        {
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("gbk");
            XMLWriter writer = new XMLWriter(new FileWriter(strFilePath), format);
            writer.write(document);
            writer.flush();
            writer.close();
            theResult = true;
        } catch (Exception e)
        {
            theResult = false;
        }
        return theResult;
    }

    /**
     * 用于在本地磁盘上创建一个简单的 xml 格式的文本文件.
     *
     * @param strFilePath
     *            XML 文件的路径.
     * @return boolean true 为创建成功; false 为创建失败.
     */
    public boolean createXmlFile(String strFilePath)
    {
        boolean theResult = false;
        try
        {
            Document document = this.createNewSimpleDocument();
          
            if (this.saveXmlToFile(strFilePath, document))
            {
                theResult = true;
            } else
            {
                theResult = false;
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }

        return theResult;
    }

    /**
     * 删除本地磁盘上的一个 xml 文件.
     *
     * @param strFilePath
     *            文件路径
     * @return boolean true 为成功; false 为失败.
     */
    public boolean deleteXmlFile(String strFilePath)
    {
        boolean theResult = false;
        try
        {
            if (strFilePath.matches(".+\\.xml") == true)
            {
                File file = new File(strFilePath);
                file.delete();
            }
            theResult = true;
        } catch (Exception e)
        {
            theResult = false;
        }
        return theResult;
    }

    /**
     * 创建一个新的 document. XML编码是GBK
     *
     * @return document XML 文档
     */
    public Document createNewDocument()
    {
        Document theResult = null;

        // Document document = DocumentHelper.createDocument();
        Document document = this.convertStringToDocument("<?xml version=\"1.0\" encoding=\"gbk\"?><root></root>");
        // Element root = document.addElement("root");
        Element root = document.getRootElement();
        // (root.addElement("row")).addAttribute("id", "1");
        (root.addElement("documentAttribute")).addAttribute("maxId", "0");
        (root.addElement("field")).addAttribute("id", "int");
        theResult = document;

        return theResult;
    }

    /**
     * 创建一个新的, 最简单的 document. XML编码是GBK
     *
     * @return document XML 文档
     */
    public Document createNewSimpleDocument()
    {
        Document theResult = null;
        Document document = this.convertStringToDocument("<?xml version=\"1.0\" encoding=\"gbk\"?><root></root>");
        theResult = document;
        return theResult;
    }

    /**
     * 将 xml 通过 xslt 转换成 xhtml .
     *
     * @param document
     *            要转换的文档
     * @param stylesheetUrl
     *            样式文件所在的位置
     * @return String 转换好的xhtml.
     * @exception Exception
     *                转换失败将抛出 Exception 异常.
     */
    public String transformToHtml(Document document, URL stylesheetUrl) throws Exception
    {
        String theResult = "";
        try
        {
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(new StreamSource(stylesheetUrl.openStream()));
            DocumentSource source = new DocumentSource(document);
            DocumentResult result = new DocumentResult();
            transformer.transform(source, result);

            StringWriter sw = new StringWriter();
            OutputFormat format = OutputFormat.createPrettyPrint();//.createCompactFormat();
//            format.setXHTML(true);
            format.setExpandEmptyElements(true);
            HTMLWriter writer = new HTMLWriter(sw, format);
            writer.write(result.getDocument());
            writer.flush();
            theResult = sw.toString();
        } catch (Exception e)
        {
         theResult = e.getMessage();
            e.printStackTrace();
            throw e;
        }
        return theResult;
    }

    /**
     * 将 xml 通过 xslt 转换成 xhtml .
     *
     * @param document
     *            要转换的文档
     * @param stylesheetFilePath
     *            样式文件所在的位置, 相对路径和绝对路径均可.
     * @return String 转换好的xhtml.
     * @exception Exception
     *                转换失败将抛出 Exception 异常.
     */
    public String transformToHtml(Document document, String stylesheetFilePath) throws Exception
    {
        String theResult = "";
        try
        {
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(new StreamSource(stylesheetFilePath));
            DocumentSource source = new DocumentSource(document);
            DocumentResult result = new DocumentResult();
            transformer.transform(source, result);

            StringWriter sw = new StringWriter();
            OutputFormat format = OutputFormat.createPrettyPrint();//.createCompactFormat();
            format.setExpandEmptyElements(true);
//            format.setXHTML(true);
            HTMLWriter writer = new HTMLWriter(sw, format);
            writer.write(result.getDocument());
            writer.flush();
            theResult = sw.toString();
        } catch (Exception e)
        {
         theResult = e.getMessage();
            e.printStackTrace();
            throw e;
        }
        return theResult;
    }

    public String transformToHtml(Document document, Reader reader) throws Exception
    {
        String theResult = "";
        try
        {
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(new StreamSource(reader));
            DocumentSource source = new DocumentSource(document);
            DocumentResult result = new DocumentResult();
            transformer.transform(source, result);

            StringWriter sw = new StringWriter();
            OutputFormat format = OutputFormat.createPrettyPrint();//.createCompactFormat();
            format.setExpandEmptyElements(true);
//            format.setXHTML(true);
            HTMLWriter writer = new HTMLWriter(sw, format);
            writer.write(result.getDocument());
            writer.flush();
            theResult = sw.toString();
        } catch (Exception e)
        {
         theResult = e.getMessage();
            e.printStackTrace();
            throw e;
        }
        return theResult;
    }
   
    /**
     * 将 document 转换为字符串.
     *
     * @param document
     *            要转换的文档
     * @param encoding
     *            XML 的编码. gb2312, gbk, gb18030, utf-8 等.
     * @return String XML 格式的文本.
     */
    public String convertDocumentToString(Document document, String encoding)
    {
        String theResult = null;
        if (encoding == null || encoding.equals("")) encoding = "gbk";

        StringWriter sw = new StringWriter();
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setExpandEmptyElements(true);
        format.setEncoding(encoding);
        XMLWriter writer = new XMLWriter(sw, format);
        try
        {
            writer.write(document);
            writer.flush();
        } catch (Exception e)
        {
        }
        theResult = sw.toString();
        return theResult;
    }

    /**
     * 将字符串转换为 document.
     *
     * @param strXml
     *            XML 格式的文本.
     * @return Document 失败将返回null.
     */
    public Document convertStringToDocument(String strXml)
    {
        Document theResult = null;
        try
        {
            theResult = DocumentHelper.parseText(strXml);
        } catch (Exception e)
        {
        }
        return theResult;
    }

    /**
     * 从 document 中提取全部row节点的数据.
     *
     * @param document
     *            要进行提取的文档.
     * @return LinkedList 数据保存到一个链接列表.
     */
    public LinkedList getAllXmlRowDataToLinkedList(Document document)
    {
        LinkedList theResult = new LinkedList();
        theResult = getAllXmlDataToLinkedList(document, "//row");
        return theResult;
    }

    /**
     * 从 document 中提取全部符合条件的数据.
     *
     * @param document
     *            要进行提取的文档.
     * @param strCondition
     *            条件. 比如 "//row" 将提取全部row节点的数据.
     * @return LinkedList 数据保存到一个链接列表.
     */
    public LinkedList getAllXmlDataToLinkedList(Document document, String strCondition)
    {
        LinkedList<HashMap> theResult = new LinkedList<HashMap>();

        // 提取所有符合条件数据
        List list_row = document.selectNodes(strCondition);
        Iterator iterator_row = list_row.iterator();
        for (int index_row = 1; iterator_row.hasNext(); index_row++)
        {
            Element element = (Element) iterator_row.next();
            HashMap<String, String> theHashMap = new HashMap<String, String>();
            theHashMap.put("", element.getText());
            for (Iterator i = element.attributeIterator(); i.hasNext();)
            {
                Attribute attribute = (Attribute) i.next();
                theHashMap.put(attribute.getName(), attribute.getValue());
            }
            for (Iterator i = element.elementIterator(); i.hasNext();)
            {
                try
                {
                    Element element2 = (Element) i.next();
                    theHashMap.put(element2.getName(), element2.getText());
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
            theResult.addLast(theHashMap);
        }
        return theResult;
    }

    /**
     * 提取比较简单的数据. 提取特定元素下的一个属性值或节点值.
     *
     * @param document
     *            要提取的文档.
     * @param strCondition
     *            选择条件. 如"//row[@name='jacky']".
     * @param key
     *            属性名或子元素名. null 或 空字符串表示直接取该元素下的值.
     * @return String 如果失败将返回空字符串.
     */
    public String getSingleXmlData(Document document, String strCondition, String key)
    {
        String theResult = "";
        Element element = (Element) document.selectSingleNode(strCondition);
        if (element != null)
        {
            if (key == null || key.equals(""))
            {
                theResult = element.getText();
            } else
            {
                theResult = element.attributeValue(key);
                if (theResult == null || theResult.equals(""))
                {
                    Element element_temp = (Element) element.selectSingleNode("./" + key);
                    if (element_temp != null)
                    {
                        theResult = element_temp.getText();
                    }
                }
            }
        }
        if (theResult == null) theResult = "";
        return theResult;
    }

    /**
     * 根据 row 元素的 id 提取一个row元素的数据. 提取row元素下的一个属性值或节点值.
     *
     * @param document
     *            要提取的文档.
     * @param rowId
     *            row 的属性 id 值.
     * @param key
     *            属性名或节点名.
     * @return String 如果失败将返回空字符串.
     */
    public String getSingleXmlRowDataById(Document document, int rowId, String key)
    {
        String theResult = "";
        theResult = this.getSingleXmlData(document, "//row[@id=" + rowId + "]", key);
        return theResult;
    }

    /**
     * 取得xml中field的各属性的值.
     *
     * @param document
     *            要提取的文档.
     * @return HashMap 失败将返回null.
     */
    public HashMap getXmlFieldAttribute(Document document)
    {
        HashMap theResult = null;

        Element element_field = (Element) document.selectSingleNode("//field");
        String[] fieldNameArray = new String[element_field.attributeCount()];
        if (element_field != null)
        {
            HashMap<String, Object> hashMap_field = new HashMap<String, Object>();
            int index = 0;
            for (Iterator i = element_field.attributeIterator(); i.hasNext();)
            {
                Attribute attribute = (Attribute) i.next();
                fieldNameArray[index++] = attribute.getName();
                hashMap_field.put(attribute.getName(), attribute.getValue());
            }
            hashMap_field.put("fieldNameArray", fieldNameArray);
            theResult = hashMap_field;
        }

        return theResult;
    }

    /**
     * 设置单一节点的值. 如果key不存在就会自动创建.
     *
     * @param document
     *            要设置的文档.
     * @param strCondition
     *            条件.
     * @param key
     *            属性或节点名. key 为 null 或 空字符串时 value 会直接保存到元素下.
     * @param value
     *            要设置的值.
     * @param isAttribute
     *            true 将保存为属性形式; false 将保存为节点形式.
     * @return true 为成功; false 为失败.
     */
    public boolean setSingleXmlData(Document document, String strCondition, String key, String value, boolean isAttribute)
    {
        boolean theResult = false;

        Element element = (Element) document.selectSingleNode(strCondition);
        if (element != null)
        {
            if (key == null || key.equals(""))
            {
                element.clearContent();
                element.addCDATA(value);
            } else if (isAttribute)
            {
                element.addAttribute(key, value);
            } else
            {
                Attribute attribute_remove = element.attribute(key);
                if (attribute_remove != null) element.remove(attribute_remove); // 删除以属性方式保存的值
                Element element_temp = (Element) element.selectSingleNode("./" + key);
                if (element_temp == null)
                {
                    element.addElement(key).addCDATA(value);
                } else
                {
                    element_temp.clearContent();
                    element_temp.addCDATA(value);
                }
            }
            theResult = true;
        }
        return theResult;
    }

    /**
     * 设置单一row节点的值. 如果key不存在就会自动创建.
     *
     * @param document
     *            要设置的文档.
     * @param rowId
     *            row 的 id.
     * @param key
     *            属性或节点名.
     * @param value
     *            要设置的值.
     * @param isAttribute
     *            true 将保存为属性形式; false 将保存为节点形式.
     * @return true 为成功; false 为失败.
     */
    public boolean setSingleXmlRowDataById(Document document, int rowId, String key, String value, boolean isAttribute)
    {
        boolean theResult = false;
        theResult = setSingleXmlData(document, "//row[@id=" + rowId + "]", key, value, isAttribute);
        return theResult;
    }

    /**
     * 得到row的记录数.
     *
     * @param document
     *            要进行统计的文档.
     * @return row 的记录数.
     */
    public int getXmlRowCount(Document document)
    {
        int theResult = 0;
        theResult = getXmlElementCount(document, "//row");
        return theResult;
    }

    /**
     * 得到条件下元素的个数.
     *
     * @param document
     *            要进行统计的文档.
     * @return 记录数.
     */
    public int getXmlElementCount(Document document, String strCondition)
    {
        int theResult = 0;
        theResult = document.selectNodes(strCondition).size();
        return theResult;
    }

    /**
     * 新建 row 节点,id 自动分配.
     *
     * @param document
     *            要新建节点的文档.
     * @return 新建节点的 id 号.
     */
    public int createSingleRow(Document document)
    {
        int theResult = 0;
        int newId = 0;
        Element element_new = document.getRootElement().addElement("row");
        Element element_documentAttribute = (Element) document.selectSingleNode("//documentAttribute");
        if (element_documentAttribute != null)
        {
            int maxId = Integer.parseInt(element_documentAttribute.attributeValue("maxId"));
            newId = maxId + 1;
            element_new.addAttribute("id", String.valueOf(newId));
            element_documentAttribute.addAttribute("maxId", String.valueOf(newId));
            theResult = newId;
        } else
        {
            theResult = -1;
        }
        return theResult;
    }

    /**
     * 新建 root 下的一个节点.
     *
     * @param document
     *            要新建的文档.
     * @param elementName
     *            节点名.
     * @return true 为成功; false 为失败.
     */
    public boolean createSingleElement(Document document, String elementName)
    {
        boolean theResult = false;
        try
        {
             Element element_new = document.getRootElement().addElement(elementName);
            theResult = true;
        } catch (Exception e)
        {
            System.out.println(e);
        }
        return theResult;
    }

    /**
     * 建新节点, 并初始化一些属性.
     *
     * @param document
     *            要新建节点的文档.
     * @param elementName
     *            节点名.
     * @param attributeName
     *            属性名.
     * @param attributeValue
     *            属性值.
     * @return true 为成功; false 为失败.
     */
    public boolean createSingleElementWithAttribute(Document document, String elementName, String attributeName, String attributeValue)
    {
        boolean theResult = false;

        try
        {
            Element element_new = document.getRootElement().addElement(elementName);
            element_new.addAttribute(attributeName, attributeValue);
            theResult = true;
        } catch (Exception e)
        {
            System.out.println(e);
        }
        return theResult;
    }

    public boolean createSingleElementWithText(Document document, String elementName, String text)
    {
        boolean theResult = false;

        try
        {
            Element element_new = document.getRootElement().addElement(elementName);
            element_new.addText(text);
            theResult = true;
        } catch (Exception e)
        {
            System.out.println(e);
        }
        return theResult;
    }
   
    /**
     * 根据 row id 删除一个row节点.
     *
     * @param document
     *            要操作的文档.
     * @param id
     *            row id.
     * @return true 为成功; false 为失败.
     */
    public boolean removeSingleRowById(Document document, int id)
    {
        boolean theResult = false;
        theResult = this.removeSingleElement(document, "//row[@id=" + id + "]");
        return theResult;
    }

    /**
     * 根据条件删除一个节点.
     *
     * @param document
     *            要操作的文档.
     * @param strCondition
     *            条件.
     * @return true 为成功; false 为失败.
     */
    public boolean removeSingleElement(Document document, String strCondition)
    {
        boolean theResult = false;
        Node node = document.selectSingleNode(strCondition);
        if (node != null)
        {
            document.getRootElement().remove(node);
            theResult = true;
        }
        return theResult;
    }

    /**
     * 判断元素是否存在.
     *
     * @param document
     *            要操作的文档.
     * @param strCondition
     *            条件.
     * @return true 为存在; false 为不存在.
     */
    public boolean existNode(Document document, String strCondition)
    {
        boolean theResult = false;
        Node node = document.selectSingleNode(strCondition);
        if (node != null)
        {
            theResult = true;
        }
        return theResult;
    }

    /**
     * 将数据库里的记录集转换成xml文档.
     *
     * @param rs
     *            记录集.
     * @param currentPage
     *            当然页.
     * @param pageSize
     *            每页的大小.
     * @return Document 文档.
     */
    public Document getXmlFromResultSet(ResultSet rs, int currentPage, int pageSize)
    {
     StringBuffer strXml = new StringBuffer();
     strXml.append("<?xml version=\"1.0\" encoding=\"gbk\"?><root>");
     
        ResultSetMetaData rsmd = null;
        int columnCount = 0;
        try
        {
            rsmd = rs.getMetaData();
            columnCount = rsmd.getColumnCount();

            boolean absoluteSuccess = false;
            // 对 rs 进行分页
            try
            {
                absoluteSuccess = rs.absolute(pageSize * (currentPage - 1) + 1);
            } catch (Exception e)
            {
             e.printStackTrace();
            }

            String strValue = "";
            if (absoluteSuccess)
            {
                for (int i = 0; i < pageSize; i++)
                {
                    strXml.append("<row rowId=\"" + (i+1) + "\">");
                    for (int j = 1; j <= columnCount; j++)
                    {
                        strValue = "";
                        try
                        {
                            strValue = rs.getString(j);
                        } catch (Exception e){}
                        strXml.append("<" + rsmd.getColumnName(j) + ">");
                        strXml.append("<![CDATA[" + strValue + "]]>");
                        strXml.append("</" + rsmd.getColumnName(j) + ">");
                    }
                    strXml.append("</row>");
                    if (!rs.next())
                    {
                        break;
                    }
                }
            }
           
        } catch (SQLException sqle)
        {
            sqle.printStackTrace();
            System.out.println(sqle.getMessage());
        } catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
        strXml.append("</root>");
        return this.convertStringToDocument(strXml.toString());
    }
   
   
    /**
     * 将 xml 文档中带有更新标记的记录更新到数据库. 元素内必须包含 dbId 属性. 如: 更新: &lt;row id="1" dbId="1001" name="jacky" email="jacky@domain.com" updateFlag="1" updateOperation="update"/&gt; 插入: &lt;row id="2" dbId="1002"
     * name="lucy" email="lucy@domain.com" updateFlag="1" updateOperation="insert"/&gt; 删除: &lt;row id="3" dbId="1003" name="temp" email="temp@domain.com" updateFlag="1" updateOperation="delete"/&gt;
     *
     * @param document
     *            要操作的文档
     * @param stmt
     *            statement
     * @param table
     *            表名
     * @param strFields
     *            字段. 格式 field1, field2, ....
     * @return true 为成功; false 为失败.
     */
    public boolean saveXmlToDataBase(Document document, Statement stmt, String table, String strFields)
    {
        boolean theResult = false;
        HashMap hashMap_field = this.getXmlFieldAttribute(document);
        String[] strArrFields = strFields.split("[, ]+");
        List list_row = document.selectNodes("//row[@updateFlag=1]");
        Iterator iterator_row = list_row.iterator();
        for (int index_row = 1; iterator_row.hasNext(); index_row++)
        {
            Element element = (Element) iterator_row.next();
            // 对不同的标记作不同的操作, 操作类型有 insert, update, delete
            String updateOperation = element.attributeValue("updateOperation");
            String dbId = element.attributeValue("dbId");
            String id = element.attributeValue("id");
            if (updateOperation != null && !updateOperation.equals(""))
            {
                // insert 操作
                if (updateOperation.equals("insert"))
                {
                    String strCols = strFields.replaceAll("'", "''");
                    // 构建 insert 语句中 values 的值
                    String strColValues = "";
                    for (int i = 0; i < strArrFields.length; i++)
                    {
                        String strCurrentField = strArrFields[i];
                        if (i != 0)
                        {
                            strColValues += ",";
                        }
                        String strValue = this.getSingleXmlData(document, "//row[@id='" + id + "']", strCurrentField);

                        // 根据field的不同属性而执行不同的操作
                        String strCurrentField_attribute = (String) hashMap_field.get(strCurrentField);
                        if (strCurrentField_attribute != null
                                && (strCurrentField_attribute.indexOf("int") > -1 || strCurrentField_attribute.indexOf("float") > -1 || strCurrentField_attribute.indexOf("money") > -1 || strCurrentField_attribute.indexOf("bit") > -1
                                        || strCurrentField_attribute.indexOf("decimal") > -1 || strCurrentField_attribute.indexOf("real") > -1))
                        {
                            if (strValue == null) strColValues += 0;
                            else strColValues += strValue;
                        } else
                        {
                            if (strValue == null) strColValues += "''";
                            else strColValues += "'" + strValue.replaceAll("'", "''") + "'";
                        }
                    }
                    try
                    {
                        // stmt.execute("insert into " + table + "(" + strCols + ") values(" + strColValues + ")");
                        stmt.addBatch("insert into " + table + "(" + strCols + ") values(" + strColValues + ")");
                        theResult = true;
                    } catch (Exception e)
                    {
                        theResult = false;
                        e.printStackTrace();
                    }
                }
                // update 操作
                if (updateOperation.equals("update") && dbId != null)
                {
                    String strUpdateSetString = "";
                    for (int i = 0; i < strArrFields.length; i++)
                    {
                        String strCurrentField = strArrFields[i];
                        if (i != 0)
                        {
                            strUpdateSetString += ",";
                        }
                        String strValue = this.getSingleXmlData(document, "//row[@id='" + id + "']", strCurrentField);

                        // 根据field的不同属性而执行不同的操作
                        String strCurrentField_attribute = (String) hashMap_field.get(strCurrentField);
                        if (strCurrentField_attribute != null
                                && (strCurrentField_attribute.indexOf("int") > -1 || strCurrentField_attribute.indexOf("float") > -1 || strCurrentField_attribute.indexOf("money") > -1 || strCurrentField_attribute.indexOf("bit") > -1
                                        || strCurrentField_attribute.indexOf("decimal") > -1 || strCurrentField_attribute.indexOf("real") > -1))
                        {
                            if (strValue == null) strUpdateSetString += strCurrentField + "=0";
                            else strUpdateSetString += strCurrentField + "=" + strValue;
                        } else
                        {
                            if (strValue == null) strUpdateSetString += strCurrentField + "=''";
                            else strUpdateSetString += strCurrentField + "='" + strValue.replaceAll("'", "''") + "'";
                        }
                    }
                    try
                    {
                        // stmt.execute("update " + table + " set " + strUpdateSetString + " where id=" + dbId);
                        stmt.addBatch("update " + table + " set " + strUpdateSetString + " where id='" + dbId + "'");
                        theResult = true;
                    } catch (Exception e)
                    {
                        theResult = false;
                        e.printStackTrace();
                    }
                }
                // delete 操作
                if (updateOperation.equals("delete") && dbId != null)
                {
                    try
                    {
                        // stmt.execute("delete from " + table + " where id=" + dbId);
                        stmt.addBatch("delete from " + table + " where id='" + dbId + "'");
                        theResult = true;
                    } catch (Exception e)
                    {
                        theResult = false;
                        e.printStackTrace();
                    }
                }
            }
        }

        try
        {
            stmt.executeBatch();
            theResult = true;
        } catch (Exception e)
        {
            theResult = false;
            e.printStackTrace();
        }
        return theResult;
    }

    /**
     * 将 xml 文档中带有更新标记的记录更新到数据库. 要更新的字段为 &lt;field&gt;里所描述的字段. 元素内必须包含 dbId 属性. 如:<br/> 更新: &lt;row id="1" dbId="1001" name="jacky" email="jacky@domain.com" updateFlag="1"
     * updateOperation="update"/&gt;<br/> 插入: &lt;row id="2" dbId="1002" name="lucy" email="lucy@domain.com" updateFlag="1" updateOperation="insert"/&gt;<br/> 删除: &lt;row id="3" dbId="1003"
     * name="temp" email="temp@domain.com" updateFlag="1" updateOperation="delete"/&gt;<br/>
     *
     * @param document
     *            要操作的文档
     * @param stmt
     *            statement
     * @param table
     *            表名
     * @return true 为成功; false 为失败.
     */
    public boolean saveXmlToDataBase(Document document, Statement stmt, String table)
    {
        boolean theResult = false;
        String strFields = "";
        Element element_field = (Element) document.selectSingleNode("//field");
        int index = 1;
        for (Iterator i = element_field.attributeIterator(); i.hasNext();)
        {
            Attribute attribute = (Attribute) i.next();
            String attribute_name = attribute.getName();
            if (attribute_name.equals("id") || attribute_name.equals("updateFlag") || attribute_name.equals("updateOperation") || attribute_name.equals("dbId"))
            {
                continue;
            }
            if (index++ != 1)
            {
                strFields += ",";
            }
            strFields += attribute_name;
        }
        theResult = saveXmlToDataBase(document, stmt, table, strFields);
        return theResult;
    }

    /**
     * 从rs中获取 xml 文档. rs 通常是带 for xml 的sql语句得出的. xml 编码为 gbk.
     *
     * @param rs
     *            记录集.
     * @return Document xml文档.
     */
    public Document getXmlFromSqlServerForXmlQuery(ResultSet rs)
    {
        Document theResult = null;
        try
        {
            Reader reader = null;
            StringBuffer sb = new StringBuffer();
            char[] charArr = new char[512];
            int readCount = 0;

            while (rs.next())
            {
                reader = rs.getCharacterStream(1);
                while ((readCount = reader.read(charArr)) > -1)
                {
                    sb.append(charArr, 0, readCount);
                }
            }

            sb.insert(0, "<?xml version=\"1.0\" encoding=\"gbk\"?><root>");
            sb.append("</root>");
            theResult = this.convertStringToDocument(sb.toString());
        } catch (Exception e)
        {
            System.out.println(e);
        }
        return theResult;
    }

    /**
     * 从rs中获取 xml 文档. xml 编码为 gbk.
     *
     * @param stmt
     *            Statement.
     * @return Document xml文档.
     */
    public Document getXmlFromSqlServerForXmlQuery(Statement stmt)
    {
        Document theResult = null;
        int i = 0;
        try
        {
            StringBuffer sb = new StringBuffer();
            ResultSet rs = null;
            Reader reader = null;
            char[] charArr = new char[512];
            int readCount = 0;
            do // 取多个结果集
            {
                rs = stmt.getResultSet();
                i++;
                if (rs != null)
                {
                    while (rs.next())
                    {
                        reader = rs.getCharacterStream(1);
                        while ((readCount = reader.read(charArr)) > -1)
                        {
                            sb.append(charArr, 0, readCount);
                        }
                    }
                }
            } while (stmt.getMoreResults());
            sb.insert(0, "<?xml version=\"1.0\" encoding=\"gbk\"?><root>");
            sb.append("</root>");
            theResult = this.convertStringToDocument(sb.toString());
        } catch (Exception e)
        {
            System.out.println(e);
        }
        return theResult;
    }

  
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值