程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> .net操縱xml文件類(c#)

.net操縱xml文件類(c#)

編輯:關於C語言

一直想要寫一個操作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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved