ASP.NETでXMLファイルを操作する方法の紹介

15159 ワード


記事の転載先:   cxi操作XMLファイルの共通方法    http://www.studyofnet.com/news/36.html
 
次はASP.NET言語で書かれた操作XMLファイルのパブリッククラスを紹介します。直接プロジェクトの中に入手できます。
 
sing System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Collections;
using System.IO;


public class XMLHealper
{
   #region     
    public XMLHealper()
   {
        FilePath = XMLPath.GetXMLPath();
        OpenXML();
   }
   #endregion

   #region     

    private XmlDocument xmlDoc = new XmlDocument();
   XmlNode xmlnode;
   XmlElement xmlelem;

   #endregion

   #region     

    private string errorMess;
    public string ErrorMess
    {
        get { return errorMess; }
        set { errorMess = value; }
    }

    private string filePath;
    public string FilePath
    {
        set { filePath = value; }
        get { return filePath; }
    }

    #endregion

    #region   XML  ,      
     /** 
    ///   XML  ,      
    /// 
    public void OpenXML()
    {
        try
        {
            if (!string.IsNullOrEmpty(FilePath))
            {
                xmlDoc.Load(filePath);
            }
            else
            {
                FilePath = string.Format(@"D:\\XMLExample.xml"); //    
                xmlDoc.Load(filePath);
            }
        }
        catch (Exception ex)
        {
            ErrorMess = ex;
        }
    }
    #endregion

    #region   Xml   
    /** 
    ///           Xml   
    /// 
    /// Xml     
    ///      
    ///     :gb2312,UTF-8     
    ///        
    /// 
    public bool CreatexmlDocument(string FileName, string rootName, string Encode)
    {
        try
        {
            XmlDeclaration xmldecl;
            xmldecl = xmlDoc.CreateXmlDeclaration("1.0", Encode, null);
            xmlDoc.AppendChild(xmldecl);
            xmlelem = xmlDoc.CreateElement("", rootName, "");
            xmlDoc.AppendChild(xmlelem);
            xmlDoc.Save(FileName);
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    #endregion

    #region      
    /** 
    ///      
    /// 
    /// 
    public DataView GetData()
    {
        xmlDoc = new XmlDocument();
        DataSet ds = new DataSet();
        StringReader read = new StringReader(xmlDoc.SelectSingleNode(FilePath).OuterXml);
        ds.ReadXml(read);
        return ds.Tables[0].DefaultView;
    }
    #endregion

    #region             
    /** 
    ///   :
    ///             
    /// 
    ///     (    ://+    )
    ///       
    /// 
    public string GetXmlNodeValue(string strNode, string strAttribute)
    {
        string strReturn = "";
        try
        {
            //          
            XmlNode xmlNode = xmlDoc.SelectSingleNode(strNode);
            //       ,           
            XmlAttributeCollection xmlAttr = xmlNode.Attributes;

            for (int i = 0; i < xmlAttr.Count; i++)
            {
                if (xmlAttr.Item(i).Name == strAttribute)
                {
                    strReturn = xmlAttr.Item(i).Value;
                }
            }
        }
        catch (XmlException xmle)
        {
            throw xmle;
        }
        return strReturn;
    }
    #endregion

    #region         
    /** 
    ///         
    /// 
    ///     
    /// 
    public string GetXmlNodeValue(string strNode)
    {
        string strReturn = String.Empty;
        try
        {
            //        
            XmlNode xmlNode = xmlDoc.SelectSingleNode(strNode);
            strReturn = xmlNode.InnerText;
        }
        catch (XmlException xmle)
        {
            System.Console.WriteLine(xmle.Message);
        }
        return strReturn;
    }
    #endregion

    #region   XML      
    /** 
    ///   XML      
    /// 
    public XmlNode GetXmlRoot()
    {
        return xmlDoc.DocumentElement;
    }
    #endregion

    #region   XML   
    /** 
    ///   XML   
    /// 
    /// 
    /// 
    public string GetNodeValue(string nodeName)
    {
        xmlDoc = new XmlDocument();
        xmlDoc.Load(FilePath);

        XmlNodeList xnl = xmlDoc.ChildNodes;
        foreach (XmlNode xnf in xnl)
        {
            XmlElement xe = (XmlElement)xnf;
            XmlNodeList xnf1 = xe.ChildNodes;
            foreach (XmlNode xn2 in xnf1)
            {
                if (xn2.InnerText == nodeName)
                {
                    XmlElement xe2 = (XmlElement)xn2;
                    return xe2.GetAttribute("value");
                }
            }
        }
        return null;
    }
    #endregion


    #region      
    /** 
    ///   :
    ///      
    /// 
    ///      
    ///    
    public void SetXmlNodeValue(string xmlNodePath, string xmlNodeValue)
    {
        try
        {
            //          
            XmlNode xmlNode = xmlDoc.SelectSingleNode(xmlNodePath);
            //     
            xmlNode.InnerText = xmlNodeValue;
        }
        catch (XmlException xmle)
        {
            throw xmle;
        }
    }
    #endregion

    #region      

    /** 
    ///           
    /// 
    public void AddParentNode(string parentNode)
    {
        XmlNode root = GetXmlRoot();
        XmlNode parentXmlNode = xmlDoc.CreateElement(parentNode);

        root.AppendChild(parentXmlNode);
    }
    #endregion

    #region                    
    /** 
    ///                    
    /// 
    public void AddChildNode(string parentNodePath, string childNodePath)
    {
        XmlNode parentXmlNode = xmlDoc.SelectSingleNode(parentNodePath);
        XmlNode childXmlNode = xmlDoc.CreateElement(childNodePath);

        parentXmlNode.AppendChild(childXmlNode);
    }
    #endregion

    #region          
    /** 
    ///          
    /// 
    public void AddAttribute(string NodePath, string NodeAttribute)
    {
        XmlAttribute nodeAttribute = xmlDoc.CreateAttribute(NodeAttribute);
        XmlNode nodePath = xmlDoc.SelectSingleNode(NodePath);
        nodePath.Attributes.Append(nodeAttribute);
    }
    #endregion

    #region               
    /** 
    ///               
    /// 
    ///        
    ///          ,True   ,False   
    ///          
    ///       ,Key     ,Value     
    ///        , Key  Name,Value  InnerText
    /// 
    public bool InsertNode(string NewNodeName, bool HasAttributes, string fatherNode, Hashtable htAtt, Hashtable htSubNode)
    {
        try
        {
            xmlDoc.Load(FilePath);
            XmlNode root = xmlDoc.SelectSingleNode(fatherNode);
            xmlelem = xmlDoc.CreateElement(NewNodeName);
            if (htAtt != null && HasAttributes)//       ,      
            {
                SetAttributes(xmlelem, htAtt);
                AddNodes(xmlelem.Name, xmlDoc, xmlelem, htSubNode);//         ,            InnerText
            }
            else
            {
                AddNodes(xmlelem.Name, xmlDoc, xmlelem, htSubNode);//       ,           
            }
            root.AppendChild(xmlelem);
            xmlDoc.Save(FilePath);
            return true;
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }
    }
    #endregion

    #region       
    /** 
    ///       
    /// 
    ///      Element
    ///     ,Key       ,Value      
    public void SetAttributes(XmlElement xe, Hashtable htAttribute)
    {
        foreach (DictionaryEntry de in htAttribute)
        {
            xe.SetAttribute(de.Key.ToString(), de.Value.ToString());
        }
    }
    #endregion

    #region           
    /** 
    ///           
    /// 
    ///       
    /// Xml   
    ///        Element
    ///      ,Key  Name  ,Value  InnerText  
    public void AddNodes(string rootNode, XmlDocument xmlDoc, XmlElement rootXe, Hashtable SubNodes)
    {
        foreach (DictionaryEntry de in SubNodes)
        {
            xmlnode = xmlDoc.SelectSingleNode(rootNode);
            XmlElement subNode = xmlDoc.CreateElement(de.Key.ToString());
            subNode.InnerText = de.Value.ToString();
            rootXe.AppendChild(subNode);
        }
    }
    #endregion

    //  

    #region         
    /** 
    ///   :
    ///         
    /// 
    ///     
    ///     
    ///    
    public void SetXmlNodeValue(string xmlNodePath, string xmlNodeAttribute, string xmlNodeAttributeValue)
    {
        try
        {
            //          
            XmlNode xmlNode = xmlDoc.SelectSingleNode(xmlNodePath);

            //       ,           
            XmlAttributeCollection xmlAttr = xmlNode.Attributes;
            for (int i = 0; i < xmlAttr.Count; i++)
            {
                if (xmlAttr.Item(i).Name == xmlNodeAttribute)
                {
                    xmlAttr.Item(i).Value = xmlNodeAttributeValue;
                    break;
                }
            }
        }
        catch (XmlException xmle)
        {
            throw xmle;
        }
    }

    #endregion

    #region     
    /** 
    ///     
    /// 
    ///            
    ///         ,Key          ,Value        
    ///             ,Key             Name,Value        InnerText
    /// 
    public bool UpdateNode(string fatherNode, Hashtable htAtt, Hashtable htSubNode)
    {
        try
        {
            xmlDoc = new XmlDocument();
            xmlDoc.Load(FilePath);
            XmlNodeList root = xmlDoc.SelectSingleNode(fatherNode).ChildNodes;
            UpdateNodes(root, htAtt, htSubNode);
            xmlDoc.Save(FilePath);
            return true;
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }
    }
    #endregion

    #region           InnerText  
    /** 
    ///           InnerText  
    /// 
    ///      
    ///            
    ///     InnerText         
    public void UpdateNodes(XmlNodeList root, Hashtable htAtt, Hashtable htSubNode)
    {
        foreach (XmlNode xn in root)
        {
            xmlelem = (XmlElement)xn;
            if (xmlelem.HasAttributes)//       ,        
            {
                foreach (DictionaryEntry de in htAtt)//       
                {
                    if (xmlelem.HasAttribute(de.Key.ToString()))//            
                    {
                        xmlelem.SetAttribute(de.Key.ToString(), de.Value.ToString());//          Value      Key
                    }
                }
            }
            if (xmlelem.HasChildNodes)//      ,        InnerText
            {
                XmlNodeList xnl = xmlelem.ChildNodes;
                foreach (XmlNode xn1 in xnl)
                {
                    XmlElement xe = (XmlElement)xn1;
                    foreach (DictionaryEntry de in htSubNode)
                    {
                        if (xe.Name == de.Key.ToString())//htSubNode   key             ,
                        {
                            xe.InnerText = de.Value.ToString();//htSubNode  Value   Key         
                        }
                    }
                }
            }
        }
    }
    #endregion


    #region          
    /** 
    ///          
    /// 
    public void DeleteAttribute(string NodePath, string NodeAttribute, string NodeAttributeValue)
    {
        XmlNodeList nodePath = xmlDoc.SelectSingleNode(NodePath).ChildNodes;

        foreach (XmlNode xn in nodePath)
        {
            XmlElement xe = (XmlElement)xn;

            if (xe.GetAttribute(NodeAttribute) == NodeAttributeValue)
            {
                xe.RemoveAttribute(NodeAttribute);//    
            }
        }
    }

    #endregion

    #region       
    /** 
    ///       
    /// 
    public void DeleteXmlNode(string tempXmlNode)
    {
        XmlNode xmlNodePath = xmlDoc.SelectSingleNode(tempXmlNode);
        xmlNodePath.ParentNode.RemoveChild(xmlNodePath);
    }

    #endregion

    #region            
    /** 
    ///            
    /// 
    ///     
    /// 
    public bool DeleteNodes(string fatherNode)
    {
        try
        {
            xmlDoc = new XmlDocument();
            xmlDoc.Load(FilePath);
            xmlnode = xmlDoc.SelectSingleNode(fatherNode);
            xmlnode.RemoveAll();
            xmlDoc.Save(FilePath);
            return true;
        }
        catch (XmlException xe)
        {
            throw new XmlException(xe.Message);
        }
    }
    #endregion


    #region     

    private string functionReturn(XmlNodeList xmlList, int i, string nodeName)
    {
        string node = xmlList[i].ToString();
        string rusultNode = "";
        for (int j = 0; j < i; j++)
        {
            if (node == nodeName)
            {
                rusultNode = node.ToString();
            }
            else
            {
                if (xmlList[j].HasChildNodes)
                {
                    functionReturn(xmlList, j, nodeName);
                }
                else
                {
                    break;
                }
            }
        }
        return rusultNode;


    }

    #endregion

    #region   XML  
    /** 
    ///   : 
    ///   XML  
    /// 
    /// 
    public void SavexmlDocument()
    {
        try
        {
            xmlDoc.Save(FilePath);
        }
        catch (XmlException xmle)
        {
            throw xmle;
        }
    }
    /** 
    ///   :   XML  
    /// 
    /// 
    public void SavexmlDocument(string tempXMLFilePath)
    {
        try
        {
            xmlDoc.Save(tempXMLFilePath);
        }
        catch (XmlException xmle)
        {
            throw xmle;
        }
    }
    #endregion
}