教程中国
PHOTOSHOP CS9.0中文版 MAYA 8.5 FOR WINDOWS Corel Painter v9.0 Flash MX2004 中文版 Illustrator cs2 中文版
VC++6.0含sp6 中英文版 VB6.0 +sp6 简体中文版 Borland Delphi 7汉化版 MSDN for vb6.0中文版 Visual Studio 2005简体
教程中国下属 文件存储共享专家BIBIDU.COM 提供大型软件,教材,源码,电影,音乐,图书等下载 更多精品请点此进入
  您目前所在位置: 教程中国 >> 编程基地 >> C# >> .net操纵xml文件类(c#) RSS订阅
.net操纵xml文件类(c#)
教程(视频,书籍)下载:  ASP.NET AutoCAD 数据库 C# ASP java photoshop 网页设计 delphi 3dmax Flash C++ VB 张孝祥 实例   更多请进入BIBIDU搜索
IT搜索引擎   

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

  1using System;
  2using System.XML;
  3using System.Web;
  4namespace solucky
  5{
  6    /**//// <summary>
  7    /// 必需用XPATH表达式来获取相应节点
  8    /// 关于xpath可以参见:
  9    /// </summary>
 10    public class MyXML
 11    {
 12        变量#region 变量
 13        /**//// <summary>
 14        /// XML文件所在路径类型
 15        /// </summary>
 16        /// <remarks>XML文件所在路径类型</remarks>
 17        public enum enumXMLPathType
 18        {   
 19            /**//// <summary>
 20            /// 绝对路径
 21            /// </summary>
 22            AbsolutePath,
 23            /**//// <summary>
 24            /// 虚拟路径
 25            /// </summary>
 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        /**//// <summary>
 37        /// 文件路径
 38        /// </summary>
 39        /// <remarks>文件路径</remarks>
 40        public string XMLFilePath
 41        {
 42            get
 43            {
 44                return this.XMLFilePath;
 45            }
 46            set
 47            {
 48                XMLFilePath = value ;
 49
 50            }
 51        }
 52
 53        /**//// <summary>
 54        /// 文件路径类型
 55        /// </summary>
 56        public enumXMLPathType XMLFilePathTyp
 57        {
 58            set
 59            {
 60                XMLFilePathType = value ;
 61            }
 62        }
 63        #endregion
 64
 65        构造函数#region 构造函数
 66        /**//// <summary>
 67        ///
 68        /// </summary>
 69        /// <param name="tempXMLFilePath"></param>
 70        public MyXML( string tempXMLFilePath )
 71        {
 72            //
 73            // TODO: 在此处添加构造函数逻辑
 74            //
 75
 76            this.XMLFilePathType = enumXMLPathType.VirtualPath ;
 77            this.XMLFilePath = tempXMLFilePath ;
 78            GetXMLDocument() ;
 79            //XMLDoc.Load( XMLFilePath ) ;
 80        }
 81   
 82        /**//// <summary>
 83        /// 构造函数
 84        /// </summary>
 85        /// <param name="tempXMLFilePath">文件路径</param>
 86        /// <param name="tempXMLFilePathType">类型</param>
 87        public MyXML( string tempXMLFilePath , enumXMLPathType tempXMLFilePathType )
 88        {
 89            //
 90            // TODO: 在此处添加构造函数逻辑
 91            //
 92            this.XMLFilePathType = tempXMLFilePathType ;
 93            this.XMLFilePath = tempXMLFilePath ;
 94            GetXMLDocument() ;
 95        }
 96        #endregion
 97
 98
 99        /**////<summary>
100        ///获取XMLDocument实体类
101        ///</summary>   
102        /// <returns>指定的XML描述文件的一个XMLdocument实例</returns>
103        private XMLDocument GetXMLDocument()
104        {
105            XMLDocument doc=null;
106
107            if( this.XMLFilePathType == enumXMLPathType.AbsolutePath )
108            {
109                doc = GetXMLDocumentFromFile( XMLFilePath ) ;
110            }
111            else if( this.XMLFilePathType == enumXMLPathType.VirtualPath )
112            {
113                doc = GetXMLDocumentFromFile(HttpContext.Current.Server.MapPath(XMLFilePath)) ;
114            }
115            return doc;
116        }
117
118        private XMLDocument GetXMLDocumentFromFile(string tempXMLFilePath)
119        {
120            string XMLFileFullPath = tempXMLFilePath ;
121            XMLDoc.Load(XMLFileFullPath) ;
122            //定义事件处理
123            XMLDoc.NodeChanged += new XMLNodeChangedEventHandler(this.nodeUpdateEvent);
124            XMLDoc.NodeInserted += new XMLNodeChangedEventHandler(this.nodeInsertEvent);
125            XMLDoc.NodeRemoved += new XMLNodeChangedEventHandler(this.nodeDeleteEvent);
126            return XMLDoc ;
127        }
128
129        读取指定节点的指定属性值#region 读取指定节点的指定属性值
130        /**//// <summary>
131        /// 功能:
132        /// 读取指定节点的指定属性值   
133        /// </summary>
134        /// <param name="strNode">节点名称</param>
135        /// <param name="strAttribute">此节点的属性</param>
136        /// <returns></returns>
137        public string GetXMLNodeAttributeValue(string strNode,string strAttribute)
138        {
139            string strReturn = "";
140            try
141            {
142                //根据指定路径获取节点
143                XMLNode XMLNode = XMLDoc.SelectSingleNode(strNode) ;
144                if (!(XMLNode==null))
145                {//获取节点的属性,并循环取出需要的属性值
146                    XMLAttributeCollection XMLAttr = XMLNode.Attributes ;
147
148                    for(int i=0 ;i<XMLAttr.Count; i++)
149                    {
150                        if (XMLAttr.Item(i).Name == strAttribute)
151                        {
152                            strReturn = XMLAttr.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        /**//// <summary>
169        /// 功能:
170        /// 读取指定节点的值   
171        /// </summary>
172        /// <param name="strNode">节点名称</param>
173        /// <returns></returns>
174        public string GetXMLNodeValue(string strNode)
175        {
176            string strReturn = String.Empty ;
177
178            try
179            {
180                //根据路径获取节点
181                XMLNode XMLNode = XMLDoc.SelectSingleNode(strNode) ;
182                if (!(XMLNode==null))
183                    strReturn = XMLNode.InnerText ;
184            }
185            catch(XMLException XMLe)
186            {
187                throw XMLe ;
188            }
189            return strReturn ;
190        }
191        #endregion
192
193        设置节点值#region 设置节点值
194        /**//// <summary>
195        /// 功能:
196        /// 设置节点值       
197        /// </summary>
198        /// <param name="strNode">节点的名称</param>
199        /// <param name="newValue">节点值</param>
200        public void SetXMLNodeValue(string XMLNodePath,string XMLNodeValue)
201        {
202            try
203            {
204                //可以批量为符合条件的节点进行付值
205                XMLNodeList XMLNode=this.XMLDoc.SelectNodes(XMLNodePath);
206                if (!(XMLNode==null))
207                {
208                    foreach(XMLNode xn in XMLNode)
209                    {
210                        xn.InnerText = XMLNodeValue ;   
211                    }
212                }
213                /**//*
214                 * 根据指定路径获取节点
215                XMLNode XMLNode = XMLDoc.SelectSingleNode(XMLNodePath) ;           
216                //设置节点值
217                if (!(XMLNode==null))
218                    XMLNode.InnerText = XMLNodeValue ;*/               
219            }
220            catch(XMLException XMLe)
221            {
222                throw XMLe ;
223            }
224        }
225        #endregion
226
227        设置节点的属性值#region 设置节点的属性值
228        /**//// <summary>
229        /// 功能:
230        /// 设置节点的属性值   
231        /// </summary>
232        /// <param name="XMLNodePath">节点名称</param>
233        /// <param name="XMLNodeAttribute">属性名称</param>
234        /// <param name="XMLNodeAttributeValue">属性值</param>
235        public void SetXMLNodeAttributeValue(string XMLNodePath,string XMLNodeAttribute,string XMLNodeAttributeValue)
236        {
237            try
238            {
239                //可以批量为符合条件的节点的属性付值
240                XMLNodeList XMLNode=this.XMLDoc.SelectNodes(XMLNodePath);
241                if (!(XMLNode==null))
242                {
243                    foreach(XMLNode xn in XMLNode)
244                    {
245                        XMLAttributeCollection XMLAttr = xn.Attributes ;
246                        for(int i=0 ; i<XMLAttr.Count ; i++)
247                        {
248                            if ( XMLAttr.Item(i).Name == XMLNodeAttribute )
249                            {
250                                XMLAttr.Item(i).Value = XMLNodeAttributeValue;
251                                break ;
252                            }
253                        }   
254                    }
255                }
256                /**//*单个节点
257                //根据指定路径获取节点
258                XMLNode XMLNode = XMLDoc.SelectSingleNode(XMLNodePath) ;
259                if (!(XMLNode==null))
260                {//获取节点的属性,并循环取出需要的属性值
261                    XMLAttributeCollection XMLAttr = XMLNode.Attributes ;
262                    for(int i=0 ; i<XMLAttr.Count ; i++)
263                    {
264                        if ( XMLAttr.Item(i).Name == XMLNodeAttribute )
265                        {
266                            XMLAttr.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        /**//// <summary>
282        /// 获取XML文件的根元素
283        /// </summary>
284        public XMLNode GetXMLRoot()
285        {
286            return XMLDoc.DocumentElement ;
287        }
288
289        /**//// <summary>
290        /// 在根节点下添加父节点
291        /// </summary>
292        public void AddParentNode(string parentNode)
293        {
294            try
295            {
296                XMLNode root = GetXMLRoot() ;
297                XMLNode parentXMLNode = XMLDoc.CreateElement(parentNode) ;
298                root.AppendChild(parentXMLNode) ;               
299            }
300            catch(XMLException XMLe)
301            {
302                throw XMLe ;
303            }
304        }
305       
306        /**//// <summary>
307        /// 向一个已经存在的父节点中插入一个子节点
308        /// </summary>
309        /// <param name="parentNodePath">父节点</param>
310        /// <param name="childNodePath">字节点名称</param>
311        public void AddChildNode( string parentNodePath,string childnodename )
312        {
313            try
314            {
315                XMLNode parentXMLNode = XMLDoc.SelectSingleNode(parentNodePath) ;               
316                if(!((parentXMLNode)==null))//如果此节点存在
317                {   
318                    XMLNode childXMLNode =  XMLDoc.CreateElement(childnodename) ;               
319                    parentXMLNode.AppendChild( childXMLNode ) ;   
320                }
321                else{//如果不存在就放父节点添加
322                    //this.GetXMLRoot().AppendChild(childXMLNode);
323                }
324                           
325            }
326            catch(XMLException XMLe)
327            {
328                throw XMLe;
329            }
330        }
331       
332        /**//// <summary>
333        /// 向一个节点添加属性
334        /// </summary>
335        /// <param name="NodePath">节点路径</param>
336        /// <param name="NodeAttribute">属性名</param>
337        public void AddAttribute( string NodePath , string NodeAttribute)
338        {
339            privateAddAttribute(NodePath,NodeAttribute,"");
340        }
341        /**//// <summary>
342        ///
343        /// </summary>
344        /// <param name="NodePath"></param>
345        /// <param name="NodeAttribute"></param>
346        /// <param name="NodeAttributeValue"></param>
347        private void privateAddAttribute( string NodePath , string NodeAttribute,string NodeAttributeValue)
348        {
349            try
350            {
351                XMLNode nodePath = XMLDoc.SelectSingleNode( NodePath ) ;
352                if (!(nodePath==null))
353                {   
354                    XMLAttribute nodeAttribute = this.XMLDoc.CreateAttribute(NodeAttribute);
355                    nodeAttribute.Value=NodeAttributeValue;
356                    nodePath.Attributes.Append(nodeAttribute) ;                       
357                }
358            }
359            catch(XMLException XMLe)
360            {
361                throw XMLe;
362            }
363        }
364        /**//// <summary>
365        ///  向一个节点添加属性,并付值
366        /// </summary>
367        /// <param name="NodePath">节点</param>
368        /// <param name="NodeAttribute">属性名</param>
369        /// <param name="NodeAttributeValue">属性值</param>
370        public void AddAttribute( string NodePath , string NodeAttribute,string NodeAttributeValue)
371        {
372            privateAddAttribute(NodePath,NodeAttribute,NodeAttributeValue);
373        }
374        #endregion
375
376        删除#region 删除
377        /**//// <summary>
378        /// 删除节点的一个属性
379        /// </summary>
380        /// <param name="NodePath">节点所在的xpath表达式</param>
381        /// <param name="NodeAttribute">属性名</param>
382        public void DeleteAttribute( string NodePath , string NodeAttribute)
383        {           
384            XMLNodeList nodePath =this.XMLDoc.SelectNodes(NodePath);           
385            if (!(nodePath==null))
386            {
387                foreach (XMLNode tempxn in nodePath)
388                {
389                    XMLAttributeCollection XMLAttr = tempxn.Attributes ;
390                    for(int i=0 ; i<XMLAttr.Count ; i++)
391                    {
392                        if ( XMLAttr.Item(i).Name == NodeAttribute)
393                        {
394                            tempxn.Attributes.RemoveAt(i);
395                            break ;
396                        }
397                    }
398                }
399            }
400        }
401       
402        /**//// <summary>
403        /// 删除节点,当其属性值等于给定的值时
404        /// </summary>
405        /// <param name="NodePath">节点所在的xpath表达式</param>
406        /// <param name="NodeAttribute">属性</param>
407        /// <param name="NodeAttributeValue">值</param>
408        public void DeleteAttribute( string NodePath , string NodeAttribute , string NodeAttributeValue)
409        {
410            XMLNodeList nodePath =this.XMLDoc.SelectNodes(NodePath);           
411            if (!(nodePath==null))
412            {
413                foreach (XMLNode tempxn in nodePath)
414                {
415                    XMLAttributeCollection XMLAttr = tempxn.Attributes ;
416                    for(int i=0 ; i<XMLAttr.Count ; i++)
417                    {
418                        if ( XMLAttr.Item(i).Name == NodeAttribute && XMLAttr.Item(i).Value==NodeAttributeValue)
419                        {
420                            tempxn.Attributes.RemoveAt(i);
421                            break ;
422                        }
423                    }
424                }
425            }
426        }
427        /**//// <summary>
428        /// 删除节点
429        /// </summary>
430        /// <param name="tempXMLNode"></param>
431        /// <remarks></remarks>
432        public void DeleteXMLNode(string tempXMLNode){   
433            XMLNodeList nodePath =this.XMLDoc.SelectNodes(tempXMLNode);
434            if (!(nodePath==null))
435            {
436                foreach(XMLNode xn in nodePath)
437                {
438                    xn.ParentNode.RemoveChild(xn);       
439                }
440            }
441        }
442
443        #endregion
444
445        XML文档事件#region XML文档事件
446        /**//// <summary>
447        ///
448        /// </summary>
449        /// <param name="src"></param>
450        /// <param name="args"></param>
451        private  void nodeInsertEvent(Object src, XMLNodeChangedEventArgs args)
452        {
453            //保存设置
454            SaveXMLDocument();
455        }
456        /**//// <summary>
457        ///
458        /// </summary>
459        /// <param name="src"></param>
460        /// <param name="args"></param>
461        private  void nodeDeleteEvent(Object src, XMLNodeChangedEventArgs args)
462        {
463            //保存设置
464            SaveXMLDocument();
465        }
466        /**//// <summary>
467        ///
468        /// </summary>
469        /// <param name="src"></param>
470        /// <param name="args"></param>
471        private  void nodeUpdateEvent(Object src, XMLNodeChangedEventArgs args)
472        {
473            //保存设置
474            SaveXMLDocument();
475        }
476        #endregion
477
478        保存XML文件#region 保存XML文件
479        /**//// <summary>
480        /// 功能:
481        /// 保存XML文件
482        ///
483        /// </summary>
484        public void SaveXMLDocument()
485        {
486            try
487            {
488                //保存设置的结果
489                if( this.XMLFilePathType == enumXMLPathType.AbsolutePath )
490                {
491                    SaveXML( XMLFilePath ) ;
492                }
493                else if( this.XMLFilePathType == enumXMLPathType.VirtualPath )
494                {
495                    SaveXML(HttpContext.Current.Server.MapPath(XMLFilePath)) ;
496                }
497            }
498            catch(XMLException XMLe)
499            {
500                throw XMLe;
501            }
502        }
503   
504        /**//// <summary>
505        /// 功能:
506        /// 保存XML文件   
507        /// </summary>
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        /**//// <summary>
521        ///
522        /// </summary>
523        /// <param name="filepath"></param>
524        private void SaveXML(string filepath)
525        {
526            XMLDoc.Save(filepath);
527        }
528
529        #endregion
530
531    }
532
533}
534
535



来源:upschool.com.cn
作者:
关键字:
发表日期:2006-9-7

网页显示有限 阅读全文请下载本文完整版WORD文档

上一篇:Visual C#中使用线程   下一篇:C#进制转换的记录


2009-1-9 20:29:23
本文的相类似文章
在学习中进步 在进步中成长 教程中国相随您的成长之路
华腾联合科技股份有限公司版权所有
广告联系:Rosibo@163.com