`
baobeituping
  • 浏览: 1064869 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

一个用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;
    }

  
}

分享到:
评论

相关推荐

    java中用dom4j读取xml

    本文将深入探讨如何使用DOM4J库来读取XML文件。 首先,让我们理解DOM4J的基本概念。DOM4J是基于DOM模型的,DOM(Document Object Model)是一种标准的API,用于解析XML文档并将其表示为一棵由节点组成的树形结构。...

    DOM4J 读取xml字符串

    **DOM4J 读取XML字符串** DOM4J 是一个非常强大的 Java XML API,它提供了丰富的功能,使得处理 XML 文件变得更加简单。DOM4J 的设计理念是简洁、灵活且高性能,它支持 SAX 和 DOM 解析,并提供了面向对象的接口。...

    dom4j 解析(读取) xml 节点数据

    接下来,我们将创建一个`SAXReader`实例,它是DOM4J中的解析器,用于读取XML文件: ```java SAXReader reader = new SAXReader(); ``` 然后,使用`reader`读取XML文件并获取`Document`对象,`Document`代表整个XML...

    利用dom4j--读取xml文件

    在本文中,我们将详细探讨如何利用DOM4J库来读取XML文件。 1. **安装DOM4J** 要使用DOM4J,首先需要将其添加到你的项目依赖中。如果你使用的是Maven,可以在`pom.xml`文件中添加以下依赖: ```xml &lt;groupId&gt;...

    dom4j的jar包(读取xml)

    DOM4J是一个强大的Java库,专门用于处理XML文档。它提供了简单且高效的API,使得XML的解析、创建、查询和修改变得容易。DOM4J的名字来源于"Document Object Model for Java",但它的功能远超出了标准DOM接口的范畴,...

    dom4j 工具类 使用例子

    总的来说,"dom4j工具类使用例子"是关于如何使用DOM4J库高效处理XML文档的实例教程。通过`Dom4jUtil.java`和`XMLResult.java`这两个类,我们可以学习到XML的读取、创建、修改等操作,掌握DOM4J的使用技巧,从而在...

    java Dom4j 无敌连环解析XML工具类

    在本教程中,我们将深入探讨如何使用DOM4J来解析XML文件,并创建一个无敌连环解析工具类。 首先,我们需要了解XML的基本概念。XML(可扩展标记语言)是一种标记语言,常用于数据交换和存储。它的结构化特性使其非常...

    DOM4J xml解析工具

    DOM4J是一个强大的Java库,专门用于处理XML文档。它提供了灵活、高性能的API,使得开发者可以方便地读取、写入、修改以及查询XML数据。DOM4J的名字来源于Document Object Model (DOM) 和 Java的结合,但它并不局限于...

    详细介绍使用Dom4j读取xml文件的方法

    本文将详细介绍如何使用Dom4j读取XML文件,并通过一个具体示例来进行深入探讨。 #### 二、环境搭建与依赖引入 在开始之前,我们需要先确保项目环境中已经包含了Dom4j库。这一步可以通过添加Dom4j的jar包至项目的类...

    DOM4J jar包 xml解析 所有的dom4j-1.6.1 dom4j-2.0.2 dom4j-2.1.1包 导入直接使用

    1. **解析XML**:DOM4J可以读取XML文件,将其转换为一个树形结构,即Document对象。解析器有SAX和DOM两种模式,SAX是事件驱动的,适用于大文件,而DOM则将整个文档加载到内存中,适合小文件。 2. **创建XML**:DOM4...

    dom4j读写xml文档实例

    要使用DOM4J读取XML文档,首先需要创建一个`SAXReader`对象,然后调用`read`方法传入XML文件路径。这将返回一个`Document`对象,我们可以从中获取所有元素信息。 ```java File file = new File("path_to_xml_file")...

    读写超大类xml文件,使用dom4j读写xml文件的工具类

    基于dom4j的读写xml文件的工具包。封装了dom4j操作xml文档的常和方法。 支持两种读写方法。1:针对小文件的读取整个文档,2:针对大文件的,逐行读取。读到几百M文件毫无压力。

    dom4j解析xml

    ### DOM4J解析XML知识点详解 #### 一、DOM4J简介 DOM4J是一个Java库,用于处理XML文档。...无论是对于开发人员还是对于那些需要频繁处理XML数据的应用程序来说,DOM4J都是一个非常有价值的工具。

    通过Dom4j创建和读取xml文件下载

    在Java编程中,DOM4J是一个非常流行的XML处理库,它提供了一套强大的API来创建、解析和操作XML文档。本教程将详细讲解如何利用DOM4J进行XML文件的创建和读取。首先,我们需要了解DOM4J的核心概念,如Element、...

    DOM4J格式化XML

    3. **DOM4J解析XML**:介绍如何使用DOM4J读取XML文件并创建Document对象,解析XML元素和属性。 4. **DOM4J格式化API**:详述DOM4J库中用于格式化XML的类和方法,如`DocumentHelper.formatDocument()`或`Element....

    XSD使用dom4j校验XML

    DOM4J是Java环境中一个强大、灵活的XML处理库,它提供了XML的读取、写入、解析和操作的能力。本篇文章将深入探讨如何利用DOM4J库来实现XSD对XML文档的校验,以确保XML文件符合预先设定的数据结构规则。 首先,理解...

    使用dom4j 和本地dom 解析xml 文件

    DOM4J是一个Java库,提供了更灵活和高效的XML处理功能,相比DOM,DOM4J提供了更丰富的API和更好的性能。它同样基于DOM模型,但提供了更友好的接口,适合处理大型XML文件。 3. **DOM4J解析步骤**: - 引入DOM4J库...

    java中dom4j读写XML

    Java中的DOM4J库是一个非常流行的、开源的Java XML API,它提供了强大的XML处理功能,包括XML的读取、创建、修改以及写入。DOM4J是基于DOM模型的,但相比标准的Java DOM,它提供了更加简洁和高效的API,使得开发者在...

    Dom4j写XML和读取XML的工具类,非常好用

    "Dom4j写XML和读取XML的工具类,非常好用" 这个标题表明我们要讨论的是一个使用Dom4j库来处理XML文档的Java工具类。Dom4j是一个非常流行的Java库,它提供了XML的解析、创建、修改以及查询功能,使得在Java中操作XML...

Global site tag (gtag.js) - Google Analytics