网站首页 > 网络编程教程 > ASP.NET教程 > .net操纵xml文件类(c#)

.net操纵xml文件类(c#)

  • 作者:互联网
  • 时间:2009-07-01 15:57:27

一直想要写一个操作XML文件的类,今天在网上找了一下,找到一个已写的差不多的类,对其进行扩展与修改,最终成了以下代码,供新手参考参考.
//
在此类中用到了XML事件.此类中对于节点的查找必需用xpath表达式,如果你对xpath表达式不了解可以查看我收藏的另外一篇文章:+XML文件操作:[学习xpath]XPath最通俗的教程+

  1using System;
  2using Sy***m.Xml;
  3using Sy***m.Web;
  4namespace solucky
  5{
  6    /**////


  7    /// 必需用XPATH表达式来获取相应节点
  8    /// 关于xpath可以参见:
  9    ///

 10    public class MyXml
 11    {
 12        变量#region 变量
 13        /**////
 14        /// xml文件所在路径类型
 15        ///

 16        /// xml文件所在路径类型
 17        public enum enumXmlPathType
 18        {   
 19            /**////
 20            /// 绝对路径
 21            ///

 22            AbsolutePath,
 23            /**////
 24            /// 虚拟路径
 25            ///

 26            VirtualPath
 27        }
 28
 29        private string xmlFilePath ;
 30        private enumXmlPathType xmlFilePathType ;
 31        private XmlDocument xmlDoc = new XmlDocument() ;
 32        #endregion
 33
 34
 35        属性#region 属性
 36        /**////
 37        /// 文件路径
 38        ///

 39        /// 文件路径
 40        public string XmlFilePath
 41        {
 42            get
 43            {
 44                return th***xmlFilePath;
 45            }
 46            set
 47            {
 48                xmlFilePath = value ;
 49
 50            }
 51        }
 52
 53        /**////
 54        /// 文件路径类型
 55        ///

 56        public enumXmlPathType XmlFilePathTyp
 57        {
 58            set
 59            {
 60                xmlFilePathType = value ;
 61            }
 62        }
 63        #endregion
 64
 65        构造函数#region 构造函数
 66        /**////
 67        ///
 68        ///

 69        ///
 70        public MyXml( string tempXmlFilePath )
 71        {
 72            //
 73            // TODO: 在此处添加构造函数逻辑
 74            //
 75
 76            th***xmlFilePathType = en***mlPathType.VirtualPath ;
 77            th***xmlFilePath = tempXmlFilePath ;
 78            GetXmlDocument() ;
 79            //***Doc.Load( xmlFilePath ) ;
 80        }
 81   
 82        /**////
 83        /// 构造函数
 84        ///

 85        /// 文件路径
 86        /// 类型
 87        public MyXml( string tempXmlFilePath , enumXmlPathType tempXmlFilePathType )
 88        {
 89            //
 90            // TODO: 在此处添加构造函数逻辑
 91            //
 92            th***xmlFilePathType = tempXmlFilePathType ;
 93            th***xmlFilePath = tempXmlFilePath ;
 94            GetXmlDocument() ;
 95        }
 96        #endregion
 97
 98
 99        /**////
100        ///获取XmlDocument实体类
101        ///
   
102        /// 指定的XML描述文件的一个xmldocument实例
103        private XmlDocument GetXmlDocument()
104        {
105            XmlDocument doc=null;
106
107            if( th***xmlFilePathType == en***mlPathType.AbsolutePath )
108            {
109                doc = GetXmlDocumentFromFile( xmlFilePath ) ;
110            }
111            else if( th***xmlFilePathType == en***mlPathType.VirtualPath )
112            {
113                doc = GetXmlDocumentFromFile(Ht***ontext.Current.Server.MapPath(xmlFilePath)) ;
114            }
115            return doc;
116        }
117
118        private XmlDocument GetXmlDocumentFromFile(string tempXmlFilePath)
119        {
120            string xmlFileFullPath = tempXmlFilePath ;
121            xm***c.Load(xmlFileFullPath) ;
122            //定义事件处理
123            xm***c.NodeChanged += new XmlNodeChangedEventHandler(th***nodeUpdateEvent);
124            xm***c.NodeInserted += new XmlNodeChangedEventHandler(th***nodeInsertEvent);
125            xm***c.NodeRemoved += new XmlNodeChangedEventHandler(th***nodeDeleteEvent);
126            return xmlDoc ;
127        }
128
129        读取指定节点的指定属性值#region 读取指定节点的指定属性值
130        /**////
131        /// 功能:
132        /// 读取指定节点的指定属性值   
133        ///

134        /// 节点名称
135        /// 此节点的属性
136        ///
137        public string GetXmlNodeAttributeValue(string strNode,string strAttribute)
138        {
139            string strReturn = "";
140            try
141            {
142                //根据指定路径获取节点
143                XmlNode xmlNode = xm***c.SelectSingleNode(strNode) ;
144                if (!(xmlNode==null))
145                {//获取节点的属性,并循环取出需要的属性值
146                    XmlAttributeCollection xmlAttr = xm***de.Attributes ;
147
148                    for(int i=0 ;i<xm***tr.Count; i++)
149                    {
150                        if (xm***tr.Item(i).Name == strAttribute)
151                        {
152                            strReturn = xm***tr.Item(i).Value ;
153                            break;
154                        }
155                    }
156                }
157            }
158            catch(XmlException xmle)
159            {
160                throw xmle ;
161            }
162            return strReturn ;
163        }
164        #endregion
165
166
167        读取指定节点的值#region 读取指定节点的值
168        /**////
169        /// 功能:
170        /// 读取指定节点的值   
171        ///

172        /// 节点名称
173        ///
174        public string GetXmlNodeValue(string strNode)
175        {
176            string strReturn = St***g.Empty ;
177
178            try
179            {
180                //根据路径获取节点
181                XmlNode xmlNode = xm***c.SelectSingleNode(strNode) ;
182                if (!(xmlNode==null))
183                    strReturn = xm***de.InnerText ;
184            }
185            catch(XmlException xmle)
186            {
187                throw xmle ;
188            }
189            return strReturn ;
190        }
191        #endregion
192
193        设置节点值#region 设置节点值
194        /**////
195        /// 功能:
196        /// 设置节点值       
197        ///

198        /// 节点的名称
199        /// 节点值
200        public void SetXmlNodeValue(string xmlNodePath,string xmlNodeValue)
201        {
202            try
203            {
204                //可以批量为符合条件的节点进行付值
205                XmlNodeList xm***de=t***.xmlDoc.SelectNodes(xmlNodePath);
206                if (!(xmlNode==null))
207                {
208                    foreach(XmlNode xn in xmlNode)
209                    {
210                        xn***nerText = xmlNodeValue ;   
211                    }
212                }
213                /**//*
214                 * 根据指定路径获取节点
215                XmlNode xmlNode = xm***c.SelectSingleNode(xmlNodePath) ;           
216                //设置节点值
217                if (!(xmlNode==null))
218                    xm***de.InnerText = xmlNodeValue ;*/               
219            }
220            catch(XmlException xmle)
221            {
222                throw xmle ;
223            }
224        }
225        #endregion
226
227        设置节点的属性值#region 设置节点的属性值
228        /**////
229        /// 功能:
230        /// 设置节点的属性值   
231        ///

232        /// 节点名称
233        /// 属性名称
234        /// 属性值
235        public void SetXmlNodeAttributeValue(string xmlNodePath,string xmlNodeAttribute,string xmlNodeAttributeValue)
236        {
237            try
238            {
239                //可以批量为符合条件的节点的属性付值
240                XmlNodeList xm***de=t***.xmlDoc.SelectNodes(xmlNodePath);
241                if (!(xmlNode==null))
242                {
243                    foreach(XmlNode xn in xmlNode)
244                    {
245                        XmlAttributeCollection xmlAttr = xn***tributes ;
246                        for(int i=0 ; i<xm***tr.Count ; i++)
247                        {
248                            if ( xm***tr.Item(i).Name == xmlNodeAttribute )
249                            {
250                                xm***tr.Item(i).Value = xmlNodeAttributeValue;
251                                break ;
252                            }
253                        }   
254                    }
255                }
256                /**//*单个节点
257                //根据指定路径获取节点
258                XmlNode xmlNode = xm***c.SelectSingleNode(xmlNodePath) ;
259                if (!(xmlNode==null))
260                {//获取节点的属性,并循环取出需要的属性值
261                    XmlAttributeCollection xmlAttr = xm***de.Attributes ;
262                    for(int i=0 ; i<xm***tr.Count ; i++)
263                    {
264                        if ( xm***tr.Item(i).Name == xmlNodeAttribute )
265                        {
266                            xm***tr.Item(i).Value = xmlNodeAttributeValue;
267                            break ;
268                        }
269                    }   
270                }
271                */
272            }
273            catch(XmlException xmle)
274            {
275                throw xmle ;
276            }
277        }
278        #endregion
279
280        添加#region 添加
281        /**////
282        /// 获取XML文件的根元素
283        ///

284        public XmlNode GetXmlRoot()
285        {
286            return xm***c.DocumentElement ;
287        }
288
289        /**////
290        /// 在根节点下添加父节点
291        ///

292        public void AddParentNode(string parentNode)
293        {
294            try
295            {
296                XmlNode root = GetXmlRoot() ;
297                XmlNode parentXmlNode = xm***c.CreateElement(parentNode) ;
298                ro***AppendChild(parentXmlNode) ;               
299            }
300            catch(XmlException xmle)
301            {
302                throw xmle ;
303            }
304        }
305       
306        /**////
307        /// 向一个已经存在的父节点中插入一个子节点
308        ///

309        /// 父节点
310        /// 字节点名称
311        public void AddChildNode( string parentNodePath,string childnodename )
312        {
313            try
314            {
315                XmlNode parentXmlNode = xm***c.SelectSingleNode(parentNodePath) ;               
316                if(!((parentXmlNode)==null))//如果此节点存在
317                {   
318                    XmlNode childXmlNode =  xm***c.CreateElement(childnodename) ;               
319                    pa***tXmlNode.AppendChild( childXmlNode ) ;   
320                }
321                else{//如果不存在就放父节点添加
322                    //***s.GetXmlRoot().AppendChild(childXmlNode);
323                }
324                           
325            }
326            catch(XmlException xmle)
327            {
328                throw xmle;
329            }
330        }
331       
332        /**////
333        /// 向一个节点添加属性
334        ///

335        /// 节点路径
336        /// 属性名
337        public void AddAttribute( string NodePath , string NodeAttribute)
338        {
339            privateAddAttribute(NodePath,NodeAttribute,"");
340        }
341        /**////
342        ///
343        ///

344        ///
345        ///
346        ///
347        private void privateAddAttribute( string NodePath , string NodeAttribute,string NodeAttributeValue)
348        {
349            try
350            {
351                XmlNode nodePath = xm***c.SelectSingleNode( NodePath ) ;
352                if (!(nodePath==null))
353                {   
354                    XmlAttribute nodeAttribute = th***xmlDoc.CreateAttribute(NodeAttribute);
355                    no***ttribute.Value=NodeAttributeValue;
356                    no***ath.Attributes.Append(nodeAttribute) ;                       
357                }
358            }
359            catch(XmlException xmle)
360            {
361                throw xmle;
362            }
363        }
364        /**////
365        ///  向一个节点添加属性,并付值
366        ///

367        /// 节点
368        /// 属性名
369        /// 属性值
370        public void AddAttribute( string NodePath , string NodeAttribute,string NodeAttributeValue)
371        {
372            privateAddAttribute(NodePath,NodeAttribute,NodeAttributeValue);
373        }
374        #endregion
375
376        删除#region 删除
377        /**////
378        /// 删除节点的一个属性
379        ///

380        /// 节点所在的xpath表达式
381        /// 属性名
382        public void DeleteAttribute( string NodePath , string NodeAttribute)
383        {           
384            XmlNodeList nodePath =t***.xmlDoc.SelectNodes(NodePath);           
385            if (!(nodePath==null))
386            {
387                foreach (XmlNode tempxn in nodePath)
388                {
389                    XmlAttributeCollection xmlAttr = tempxn***tributes ;
390                    for(int i=0 ; i<xm***tr.Count ; i++)
391                    {
392                        if ( xm***tr.Item(i).Name == NodeAttribute)
393                        {
394                            tempxn***tributes.RemoveAt(i);
395                            break ;
396                        }
397                    }
398                }
399            }
400        }
401       
402        /**////
403        /// 删除节点,当其属性值等于给定的值时
404        ///

405        /// 节点所在的xpath表达式
406        /// 属性
407        ///
408        public void DeleteAttribute( string NodePath , string NodeAttribute , string NodeAttributeValue)
409        {
410            XmlNodeList nodePath =t***.xmlDoc.SelectNodes(NodePath);           
411            if (!(nodePath==null))
412            {
413                foreach (XmlNode tempxn in nodePath)
414                {
415                    XmlAttributeCollection xmlAttr = tempxn***tributes ;
416                    for(int i=0 ; i<xm***tr.Count ; i++)
417                    {
418                        if ( xm***tr.Item(i).Name == NodeAttribute && xm***tr.Item(i).Value==NodeAttributeValue)
419                        {
420                            tempxn***tributes.RemoveAt(i);
421                            break ;
422                        }
423                    }
424                }
425            }
426        }
427        /**////
428        /// 删除节点
429        ///

430        ///
431        ///
432        public void DeleteXmlNode(string tempXmlNode){   
433            XmlNodeList nodePath =t***.xmlDoc.SelectNodes(tempXmlNode);
434            if (!(nodePath==null))
435            {
436                foreach(XmlNode xn in nodePath)
437                {
438                    xn***rentNode.RemoveChild(xn);       
439                }
440            }
441        }
442
443        #endregion
444
445        XML文档事件#region XML文档事件
446        /**////
447        ///
448        ///

449        ///
450        ///
451        private  void nodeInsertEvent(Object src, XmlNodeChangedEventArgs args)
452        {
453            //保存设置
454            SaveXmlDocument();
455        }
456        /**////
457        ///
458        ///

459        ///
460        ///
461        private  void nodeDeleteEvent(Object src, XmlNodeChangedEventArgs args)
462        {
463            //保存设置
464            SaveXmlDocument();
465        }
466        /**////
467        ///
468        ///

469        ///
470        ///
471        private  void nodeUpdateEvent(Object src, XmlNodeChangedEventArgs args)
472        {
473            //保存设置
474            SaveXmlDocument();
475        }
476        #endregion
477
478        保存XML文件#region 保存XML文件
479        /**////
480        /// 功能:
481        /// 保存XML文件
482        ///
483        ///

484        public void SaveXmlDocument()
485        {
486            try
487            {
488                //保存设置的结果
489                if( th***xmlFilePathType == en***mlPathType.AbsolutePath )
490                {
491                    Savexml( xmlFilePath ) ;
492                }
493                else if( th***xmlFilePathType == en***mlPathType.VirtualPath )
494                {
495                    Savexml(Ht***ontext.Current.Server.MapPath(xmlFilePath)) ;
496                }
497            }
498            catch(XmlException xmle)
499            {
500                throw xmle;
501            }
502        }
503   
504        /**////
505        /// 功能:
506        /// 保存XML文件   
507        ///

508        public void SaveXmlDocument(string tempXMLFilePath)
509        {
510            try
511            {
512                //保存设置的结果
513                Savexml(tempXMLFilePath);
514            }
515            catch(XmlException xmle)
516            {
517                throw xmle;
518            }
519        }
520        /**////
521        ///
522        ///

523        ///
524        private void Savexml(string filepath)
525        {
526            xm***c.Save(filepath);
527        }
528
529        #endregion
530
531    }
532
533}
534
535