操作xml文件或者XML内存对象,得到某个节点的值

package com.trs.rws.tools;
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;

import org.w3c.dom.*;
import com.trs.tool.*;
import com.trs.tool.Logger;
import com.trs.tool.TException;

/**
 * <p>Title: xml操作类</p>
 * <p>Description: 操作xml文件或者XML内存对象,得到某个节点的值!</p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: www.trs.com.cn</p>
 * @author huanghongfa
 * @version 1.0
 */

public class OperateXML
{
  private Document docDOMSource = null;

  /**
   * 构造函数
   */
  public OperateXML()
  {
    super ();
  }

  /**
   * 构造函数
   * @param docDOMSource 内存中Document对象
   */
  public OperateXML(Document docDOMSource)
  {
    super ();
    this.docDOMSource = docDOMSource;
  }

  /**
   * 设置DOMSource,以便对这个xml对象进行操作
   * @param docDOMSource 内存中Document对象
   */
  public void setDOMSource(Document docDOMSource)
  {
    this.docDOMSource = docDOMSource;
  }

  /**
   * 设置DOMSource,以便对这个xml对象进行操作
   * @param fDOMSource xml文件
   */
  public void setDOMSource(File fDOMSource)
      throws TException
  {
    try
    {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ();
      DocumentBuilder builder = factory.newDocumentBuilder ();
      Document doc = builder.parse (fDOMSource);
      doc.normalize ();
      this.docDOMSource = doc;
    }
    catch(javax.xml.parsers.ParserConfigurationException pce)
    {
    	pce.printStackTrace();
 //     throw new TException ("The parser was not configured correctly.", "", pce);
      //System.out.println("The parser was not configured correctly.");
    }
    catch(java.io.IOException ie)
    {
    	ie.printStackTrace();
 //     throw new TException ("Cannot read input file.", "", ie);
      //System.out.println("Cannot read input file.");
    }
    catch(org.xml.sax.SAXException se)
    {
    	se.printStackTrace();
//      throw new TException ("Problem parsing the file.", "", se);
      //System.out.println("Problem parsing the file.");
    }
    catch(java.lang.IllegalArgumentException ae)
    {
    	ae.printStackTrace();
//      throw new TException ("Please specify an XML source.", "", ae);
      //System.out.println("Please specify an XML source.");
    }
  }

  /**
   * 设置DOMSource,以便对这个xml对象进行操作
   * @param ByteArrayInputStream 可以通过如下方法得到
   * ByteArrayInputStream bais = new ByteArrayInputStream(strGet.getBytes("GBK"));
   */
  public void setDOMSource(ByteArrayInputStream bais)
      throws TException
  {
    try
    {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ();
      DocumentBuilder builder = factory.newDocumentBuilder ();
      Document doc = builder.parse (bais);
      doc.normalize ();
      this.docDOMSource = doc;
    }
    catch(Exception ex)
    {
    	ex.printStackTrace();
//      Logger.log("解释xml的时候发生错误,输入的字符串不符合xml格式!" + ex.toString (),"exp");
//      throw new TException ("解释xml的时候发生错误,输入的字符串不符合xml格式!" + ex.toString (), "");
    }
  }

  /**
   * 设置DOMSource,以便对这个xml对象进行操作
   * @param strXMLFileName xml文件名称,如:C:\\temp\\test.xml 格式
   */
  public void setDOMSource(String strXMLFileName)
      throws TException
  {
    try
    {
      File fDOMSource = new File (strXMLFileName);
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ();
      DocumentBuilder builder = factory.newDocumentBuilder ();
      Document doc = builder.parse (fDOMSource);
      doc.normalize ();
      this.docDOMSource = doc;
    }
    catch(javax.xml.parsers.ParserConfigurationException pce)
    {
    	pce.printStackTrace();
//      throw new TException ("The parser was not configured correctly.", "OperateXML,setDOMSource()");
    }
    catch(java.io.IOException ie)
    {
    	ie.printStackTrace();
//      throw new TException ("Cannot read input file.", "OperateXML,setDOMSource()");
    }
    catch(org.xml.sax.SAXException se)
    {
    	se.printStackTrace();
//      throw new TException ("Problem parsing the file.", "OperateXML,setDOMSource()");
    }
    catch(java.lang.IllegalArgumentException ae)
    {
    	ae.printStackTrace();
//      throw new TException ("Please specify an XML source.", "OperateXML,setDOMSource()");
    }
  }
  /**
   * 设置DOMSource,以便对这个xml对象进行操作
   * @param ByteArrayInputStream 可以通过如下方法得到
   * ByteArrayInputStream bais = new ByteArrayInputStream(strGet.getBytes("GBK"));
   */
  public void setDOMSource(InputStream is)
      throws TException
  {
    try
    {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ();
      DocumentBuilder builder = factory.newDocumentBuilder ();
      Document doc = builder.parse (is);
      doc.normalize ();
      this.docDOMSource = doc;
    }
    catch(Exception ex)
    {
    	ex.printStackTrace();
//      throw new TException ("解释xml的时候发生错误,输入的XML文件流格式错误!" + ex.toString (), "");
    }
  }

  /**
   * 得到DOMSource
   * @return org.w3c.dom.Document
   */
  public Document getDOMSource()
  {
    return this.docDOMSource;
  }

  /**
   * 通过置标名称,得到该置标节点的值
   * @param strTargetName 该置标的名称
   */
  public String getValueByTargetName(String strTargetName)
  {
    String strValue = "";
    NodeList nodelist = null;
    Node node;
    try
    {
      nodelist = docDOMSource.getElementsByTagName (strTargetName.trim ());
      if(nodelist.getLength () != 0)
      {
        node = nodelist.item (0);
        nodelist = node.getChildNodes ();
        int i = nodelist.getLength ();
        if(i == 1)
        {
          if(node.getFirstChild () != null)
          {
            strValue = node.getFirstChild ().getNodeValue ();
          }
        }
        else
        {
          for(int j = 1; j < i; j++)
          {
            node = nodelist.item (j);
            if(node.getNodeType () == Node.CDATA_SECTION_NODE)
            {
              strValue = node.getNodeValue ();
              break;
            }
          }
        }
      }
      return strValue;
    }
    catch(DOMException ex)
    {
//      Logger.log(ex.getMessage(),"exp");
      return null;
    }
  }

  /**
   * 通过置标名称,得到该置标节点的值
   * @param strTargetName 该置标的名称
   */
  public Hashtable getChildrenNodeNameAndValueByTargetName(String strTargetName)
  {
    Hashtable ht = new Hashtable ();
    NodeList nodelist = null;
    Node node;
    int i, nSize;
    nodelist = docDOMSource.getElementsByTagName (strTargetName.trim ());
    if(nodelist.getLength () != 0)
    {
      node = nodelist.item (0);
      nodelist = node.getChildNodes ();
      nSize = nodelist.getLength ();
      for(i = 0; i < nSize; i++)
      {
        node = nodelist.item (i);
        if(node!=null && node.getNodeType()!=Node.TEXT_NODE)
        {
          if(node.getFirstChild ()!=null)
          {
            ht.put (node.getNodeName (), node.getFirstChild ().getNodeValue ());
          }
          else
          {
              ht.put (node.getNodeName (), "");
          }
        }
      }
    }
    return ht;
  }

  /**
   * 通过置标名称,得到该置标节点的值
   * @param strTargetName 该置标的名称
   */
  public String[] getChildrenNodeValuesByTargetName(String strTargetName)
  {
    String[] arrValue=null;
    NodeList nodeHList=null;
    NodeList nodelist = null;
    Node node;
    int i, nSize;
    nodeHList = docDOMSource.getElementsByTagName (strTargetName.trim ());
    arrValue=new String[nodeHList.getLength ()];
    if(nodeHList.getLength () != 0)
    {
      for(i=0;i<nodeHList.getLength();i++)
      {
        node = nodeHList.item (i);
        nodelist = node.getChildNodes ();
        if(nodelist.item(0)!=null)
        {
          if(nodelist.item (0).getNodeValue () == null)
          {
            arrValue[i] = "";
          }
          else
          {
            arrValue[i] = nodelist.item (0).getNodeValue ();
          }
        }
        else
        {
          arrValue[i] ="";
        }
      }
    }
    return arrValue;
  }

  /**
   * 通过置标的路径,得到该置标节点的值
   * @param strTargetPath 该置标的路径
   * @param ch 路径的隔开符号,如:可以这样调用这个方法:getValueByTargetPath("xml/test/ok",'/');
   * @return String 假如不存在,就为空“”
   */
  public String getValueByTargetPath(String strTargetPath, int ch)
  {
    String strPath = strTargetPath.trim ();
    String strTargetName = null;
    NodeList nodelist = null;
    Node node = null;
    Element element = null;
    int nPosition = 0;
    String strValue = "";

    //得到第一个节点元素(begin)
    nPosition = strPath.indexOf (ch);
    strTargetName = strPath.substring (0, nPosition);
    strPath = strPath.substring (nPosition + 1);
    nodelist = docDOMSource.getElementsByTagName (strTargetName);
    if(nodelist.getLength () == 0)
    {
      return null;
    }
    else
    {
      element = (Element) nodelist.item (0);
    }
    //得到第一个节点元素(end)

    //循环解释路径,得到最低层的节点的值(begin)
    while(!strPath.equals (""))
    {
      nPosition = strPath.indexOf (ch);
      if(nPosition == -1)
      {
        strTargetName = strPath;
        nodelist = element.getElementsByTagName (strTargetName);
        if(nodelist.getLength () == 0)
        {
          return null;
        }
        else
        {
          node = nodelist.item (0);
          nodelist = node.getChildNodes ();
          int i = nodelist.getLength ();
          if(i == 1)
          {
            if(node.getFirstChild () != null)
            {
              strValue = node.getFirstChild ().getNodeValue ();
            }
          }
          else
          {
            for(int j = 1; j < i; j++)
            {
              node = nodelist.item (j);
              if(node.getNodeType () == Node.CDATA_SECTION_NODE)
              {
                strValue = node.getNodeValue ();
                break;
              }
            }
          }
        }
        strPath = "";
      }
      else
      {
        strTargetName = strPath.substring (0, nPosition);
        nodelist = element.getElementsByTagName (strTargetName);
        if(nodelist.getLength () == 0)
        {
          return null;
        }
        else
        {
          element = (Element) nodelist.item (0);
        }
        strPath = strPath.substring (nPosition + 1);
      }
    }
    //循环解释路径,得到最低层的节点的值(end)

    return strValue;
  }

  /**
   * 通过置标名称,得到该置标在XML中是否存在.
   * @param strTargetName 该置标的名称
   */
  public int getElementExist(String strTargetName)
  {
    int int_Counts=0;
    NodeList nodelist = null;
    try
    {
      nodelist = docDOMSource.getElementsByTagName (strTargetName.trim ());
      int_Counts=nodelist.getLength ();
    }
    catch(DOMException ex)
    {
//      Logger.log (ex.getMessage (), "exp");
      int_Counts=0;
    }
    finally
    {
        return int_Counts;
    }
  }

}

你可能感兴趣的:(xml)