xml操作类,封装了常用的对XML文件的操作功能....

using System;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace WWFCommonClassLib
{
    /// <summary>
    /// 该类主要封装对XML的常用操作,需要XPath表达式来获得相应节点
    /// GeneralXu 07-04-19
    /// </summary>
    public class XmlEditClass
    {
#region 变量
        //xml文件所在路径类型
        public enum enumXmlPathType
        {
            AbsolutePath,VirtualPath //绝对路径,虚拟路径
        }
        private string xmlFilePath ;
        private enumXmlPathType xmlFilePathType ;
        private XmlDocument xmlDoc = new XmlDocument() ;
#endregion

#region 属性
        // 文件路径
        public string XmlFilePath
        {
            get{return this.xmlFilePath;}
            set{xmlFilePath = value ;}
        }
        // 文件路径类型
        public enumXmlPathType XmlFilePathType
        {
            set{xmlFilePathType = value ;}
        }
#endregion

#region 构造函数
        public XmlEditClass(string tempXmlFilePath)
        {
            //在此添加构造函数逻辑
            this.xmlFilePathType = enumXmlPathType.VirtualPath ;
            this.xmlFilePath = tempXmlFilePath ;
            GetXmlDocument() ;
        }

        public XmlEditClass(string tempXmlFilePath, enumXmlPathType tempXmlFilePathType)
        {
            //在此添加构造函数逻辑
            this.xmlFilePathType = tempXmlFilePathType ;
            this.xmlFilePath = tempXmlFilePath ;
            GetXmlDocument() ;
        }
#endregion

#region 获取XmlDocument实体类
        private XmlDocument GetXmlDocument()
        {
            XmlDocument xmlDoc=null;
            if( this.xmlFilePathType == enumXmlPathType.AbsolutePath )
            {
                xmlDoc = GetXmlDocumentFromFile( xmlFilePath ) ;
            }
            else if( this.xmlFilePathType == enumXmlPathType.VirtualPath )
            {
                xmlDoc = GetXmlDocumentFromFile(HttpContext.Current.Server.MapPath(xmlFilePath)) ;
            }
            return xmlDoc;
        }

        private XmlDocument GetXmlDocumentFromFile(string tempXmlFilePath)
        {
             string xmlFileFullPath = tempXmlFilePath ;
             xmlDoc.Load(xmlFileFullPath) ;
             //定义事件处理
             xmlDoc.NodeChanged += new XmlNodeChangedEventHandler(this.nodeUpdateEvent);
             xmlDoc.NodeInserted += new XmlNodeChangedEventHandler(this.nodeInsertEvent);
             xmlDoc.NodeRemoved += new XmlNodeChangedEventHandler(this.nodeDeleteEvent);
             return xmlDoc ;
        }

#endregion
#region 读取指定接点的属性
        public string GetXmlNodeAttributeValue(string strNode,string strAttribute)
        {
             string strReturn = "";
             try
             {
                 //根据指定路径获取节点
                 XmlNode xmlNode = xmlDoc.SelectSingleNode(strNode) ;
                 if (!(xmlNode==null))
                 {
                     //获取节点的属性,并循环取出需要的属性值
                     XmlAttributeCollection xmlAttr = xmlNode.Attributes ;
                     for(int i=0 ;i<xmlAttr.Count;i++)
                     {
                        if (xmlAttr.Item(i).Name == strAttribute)
                        {
                            strReturn = xmlAttr.Item(i).Value ;
                            break;
                        }
                     }
                 }
             }
             catch(XmlException xmle)
             {
                throw xmle ;
             }
             return strReturn ;
        }

#endregion
#region 读取指定接点的值
        public string GetXmlNodeValue(string strNode)
        {
            string strReturn = String.Empty ;
            try
            {
                //根据路径获取节点
                XmlNode xmlNode = xmlDoc.SelectSingleNode(strNode) ;
                if (!(xmlNode==null))
                strReturn = xmlNode.InnerText ;
            }
                catch(XmlException xmle)
            {
                throw xmle ;
            }
            return strReturn ;
        }       
#endregion
#region 设置指定接点的值
         public void SetXmlNodeValue(string xmlNodePath,string xmlNodeValue)
         {
            try
            {
                //可以批量为符合条件的节点进行付值
                XmlNodeList xmlNode=this.xmlDoc.SelectNodes(xmlNodePath);
                if (!(xmlNode==null))
                {
                    foreach(XmlNode xn in xmlNode)
                    {
                        xn.InnerText = xmlNodeValue ;
                    }
                }
            }
            catch(XmlException xmle)
            {
                throw xmle ;
            }
         }

#endregion
#region 设置接点属性值
        public void SetXmlNodeAttributeValue(string xmlNodePath,string xmlNodeAttribute,string xmlNodeAttributeValue)
        {
            try
            {
                //可以批量为符合条件的节点的属性付值
                XmlNodeList xmlNode=this.xmlDoc.SelectNodes(xmlNodePath);
                if (!(xmlNode==null))
                {
                    foreach(XmlNode xn in xmlNode)
                    {
                        XmlAttributeCollection xmlAttr = xn.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 获取XML文件的根元素
        public XmlNode GetXmlRoot()
        {
            return xmlDoc.DocumentElement ;
        }
#endregion

#region 在根接点下添加父接点
        public void AddParentNode(string parentNode)
        {
            try
            {
                XmlNode root = GetXmlRoot() ;
                XmlNode parentXmlNode = xmlDoc.CreateElement(parentNode) ;
                root.AppendChild(parentXmlNode) ;
            }
            catch(XmlException xmle)
            {
                throw xmle ;
            }
        }

#endregion
#region 向已经存在的父接点中插入子接点
        public void AddChildNode( string parentNodePath,string childnodename )
        {
            try
            {
                XmlNode parentXmlNode = xmlDoc.SelectSingleNode(parentNodePath) ;
                if(!((parentXmlNode)==null))//如果此节点存在
                {
                    XmlNode childXmlNode = xmlDoc.CreateElement(childnodename) ;
                    parentXmlNode.AppendChild( childXmlNode ) ;
                }
                else{
                        //如果不存在就放父节点添加
                    //this.GetXmlRoot().AppendChild(childXmlNode);
                }
            }
            catch(XmlException xmle)
            {
                throw xmle;
            }
        }

#endregion
#region 向一个接点添加属性
        public void AddAttribute( string NodePath , string NodeAttribute)
        {
            privateAddAttribute(NodePath,NodeAttribute,"");
        }
        private void privateAddAttribute( string NodePath , string NodeAttribute,string NodeAttributeValue)
        {
            try
            {
                XmlNode nodePath = xmlDoc.SelectSingleNode( NodePath ) ;
                if (!(nodePath==null))
                {
                    XmlAttribute nodeAttribute = this.xmlDoc.CreateAttribute(NodeAttribute);
                    nodeAttribute.Value=NodeAttributeValue;
                    nodePath.Attributes.Append(nodeAttribute) ;
                }
            }
            catch(XmlException xmle)
            {
                throw xmle;
            }
        }
#endregion
#region 向一个接点添加属性并赋值 
        public void AddAttribute( string NodePath , string NodeAttribute,string NodeAttributeValue)
        {
            privateAddAttribute(NodePath,NodeAttribute,NodeAttributeValue);
        }
#endregion

#region 删除属性
        public void DeleteAttribute( string NodePath , string NodeAttribute)
        {
            XmlNodeList nodePath =this.xmlDoc.SelectNodes(NodePath);
            if (!(nodePath==null))
            {
                foreach (XmlNode tempxn in nodePath)
                {
                    XmlAttributeCollection xmlAttr = tempxn.Attributes ;
                    for(int i=0 ; i<xmlAttr.Count;i++)
                    {
                        if ( xmlAttr.Item(i).Name == NodeAttribute)
                        {
                            tempxn.Attributes.RemoveAt(i);
                            break ;
                        }
                    }
                }
            }
        }
#endregion
#region 删除属性,当属性等于给定值时
        public void DeleteAttribute( string NodePath , string NodeAttribute , string NodeAttributeValue)
        {
            XmlNodeList nodePath =this.xmlDoc.SelectNodes(NodePath);
            if (!(nodePath==null))
            {
                foreach (XmlNode tempxn in nodePath)
                {
                    XmlAttributeCollection xmlAttr = tempxn.Attributes ;
                    for(int i=0 ; i<xmlAttr.Count;i++)
                    {
                        if ( xmlAttr.Item(i).Name == NodeAttribute && xmlAttr.Item(i).Value==NodeAttributeValue)
                        {
                            tempxn.Attributes.RemoveAt(i);
                            break ;
                        }
                    }
                }
            }
        }
#endregion

#region 删除接点
        public void DeleteXmlNode(string tempXmlNode)
        {
            XmlNodeList nodePath =this.xmlDoc.SelectNodes(tempXmlNode);
            if (!(nodePath==null))
            {
                foreach(XmlNode xn in nodePath)
                {
                    xn.ParentNode.RemoveChild(xn);
                }
            }
        }
#endregion

#region XML文档事件
        private void nodeInsertEvent(Object src, XmlNodeChangedEventArgs args)
        {
            //保存设置
            SaveXmlDocument();
        }
        private void nodeDeleteEvent(Object src, XmlNodeChangedEventArgs args)
        {
            //保存设置
            SaveXmlDocument();
        }
        private void nodeUpdateEvent(Object src, XmlNodeChangedEventArgs args)
        {
            //保存设置
            SaveXmlDocument();
        }
#endregion

#region 保存XML文件
        public void SaveXmlDocument()
        {
            try
            {
                //保存设置的结果
                if( this.xmlFilePathType == enumXmlPathType.AbsolutePath )
                {
                    Savexml( xmlFilePath ) ;
                }
                else if( this.xmlFilePathType == enumXmlPathType.VirtualPath )
                {
                    Savexml(HttpContext.Current.Server.MapPath(xmlFilePath)) ;
                }
            }
            catch(XmlException xmle)
            {
                throw xmle;
            }
        }
       
        public void SaveXmlDocument(string tempXMLFilePath)
        {
            try
            {
                //保存设置的结果
                Savexml(tempXMLFilePath);
            }
            catch(XmlException xmle)
            {
                throw xmle;
            }
        }
       
        private void Savexml(string filepath)
        {
            xmlDoc.Save(filepath);
        }

#endregion
#region 读取指定接点的全部子接点信息到Hashtable中
        public Hashtable getAllChildNodesInfo(string parentNodePath,string keyName,string keyValue)
        {
            Hashtable hashtable = new Hashtable();
            try
            {
                XmlNode parentXmlNode = xmlDoc.SelectSingleNode(parentNodePath);
                if (!((parentXmlNode) == null))//如果此节点存在
                {
                    foreach (XmlNode xn in parentXmlNode.ChildNodes)
                    {
                        XmlElement xe = (XmlElement)xn;
                        hashtable.Add(xe.GetAttribute(keyName).ToString(), xe.GetAttribute(keyValue).ToString());
                    }
                }
                else
                {
                    //如果不存在就放父节点添加
                    //this.GetXmlRoot().AppendChild(childXmlNode);
                }
            }
            catch (XmlException xmle)
            {
                throw xmle;
            }
            return hashtable;
        }

#endregion
#region 读取二级接点指定的属性到ArrayList中
        public ArrayList GetSecondaryNodeAttributeValue(string attributeName)
        {
            ArrayList al = new ArrayList();
            XmlNode xn = GetXmlRoot();
            XmlNodeList xnl = xn.ChildNodes;
            foreach(XmlNode tempxn in xnl)
            {
                XmlElement xe = (XmlElement)tempxn;
                al.Add(xe.GetAttribute(attributeName).ToString());
            }
            return al;
        }
#endregion
        #region 插入新的接点,并对新的接点增加属性、设置属性值
        /// <summary>
        /// GeneralXu 07-04-23
        /// </summary>
        /// <param name="parentNodePath"></param>
        /// <param name="childnodename"></param>
        /// <param name="attributeList">这里是属性和属性值列表信息,格式是“属性名:属性值”</param>
        public void AddNodeAndSetAttribulteValue(string parentNodePath, string childnodename,ArrayList attributeList)
        {
            try
            {
                XmlNode parentXmlNode = xmlDoc.SelectSingleNode(parentNodePath);
                if (!((parentXmlNode) == null))//如果此节点存在
                {
                    XmlNode childXmlNode = xmlDoc.CreateElement(childnodename);
                    if ((attributeList != null) && (attributeList.Count > 0))
                    {
                        for (int i = 0; i < attributeList.Count; i++)
                        {
                            string[] strAttriNameValue = null;
                            strAttriNameValue = attributeList[i].ToString().Split(":".ToCharArray());
                            XmlAttribute xa = xmlDoc.CreateAttribute(strAttriNameValue[0].ToString());
                            xa.Value = strAttriNameValue[1].ToString();
                            childXmlNode.Attributes.Append(xa);
                        }
                    }
                    parentXmlNode.AppendChild(childXmlNode);
                }
                else
                {
                    //如果不存在就放父节点添加
                    //this.GetXmlRoot().AppendChild(childXmlNode);
                }
            }
            catch (XmlException xmle)
            {
                throw xmle;
            }
        }
        #endregion

    }
}

posted @ 2007-04-19 23:24  GeneralXU  阅读(646)  评论(0编辑  收藏  举报