1. 程式人生 > >C#學習筆記(12)——三種方法操作XML

C#學習筆記(12)——三種方法操作XML

結點 記得 ext 應用程序 eval 資源 特性 pla cells

說明(2017-7-11 16:56:13):

原文地址:

C#中常用的幾種讀取XML文件的方法

XML文件是一種常用的文件格式,例如WinForm裏面的app.config以及Web程序中的web.config文件,還有許多重要的場所都有它的身影。Xml是Internet環境中跨平臺的,依賴於內容的技術,是當前處理結構化文檔信息的有力工具。XML是一種簡單的數據存儲語言,使用一系列簡單的標記描述數據,而這些標記可以用方便的方式建立,雖然XML占用的空間比二進制數據要占用更多的空間,但XML極其簡單易於掌握和使用。微軟也提供了一系列類庫來倒幫助我們在應用程序中存儲XML文件。

“在程序中訪問進而操作XML文件一般有兩種模型,分別是使用DOM(文檔對象模型)和流模型,使用DOM的好處在於它允許編輯和更新XML文檔,可以隨機訪問文檔中的數據,可以使用XPath查詢,但是,DOM的缺點在於它需要一次性的加載整個文檔到內存中,對於大型的文檔,這會造成資源問題。流模型很好的解決了這個問題,因為它對XML文件的訪問采用的是流的概念,也就是說,任何時候在內存中只有當前節點,但它也有它的不足,它是只讀的,僅向前的,不能在文檔中執行向後導航操作。”具體參見

在Visual C#中使用XML指南之讀取XML

下面我將介紹三種常用的讀取XML文件的方法。分別是

   1: 使用 XmlDocument
   2: 使用 XmlTextReader
   3: 使用 Linq to Xml

這裏我先創建一個XML文件,名為Book.xml下面所有的方法都是基於這個XML文件的,文件內容如下:

   1: <?xml version="1.0" encoding="utf-8"?>
   2: <bookstore>
   3:   <!--記錄書本的信息-->
   4:   <book Type="必修課" ISBN="7-111-19149-2">
   5:     <title>數據結構</title>
   6:     <author>嚴蔚敏</author>
   7:     <price>30.00</price>
   8:   </book>
   9:   <book Type="必修課" ISBN="7-111-19149-3">
  10:     <title>路由型與交換型互聯網基礎</title>
  11:     <author>程慶梅</author>
  12:     <price>27.00</price>
  13:   </book>
  14:   <book Type="必修課" ISBN="7-111-19149-4">
  15:     <title>計算機硬件技術基礎</title>
  16:     <author>李繼燦</author>
  17:     <price>25.00</price>
  18:   </book>
  19:   <book Type="必修課" ISBN="7-111-19149-5">
  20:     <title>軟件質量保證與管理</title>
  21:     <author>朱少民</author>
  22:     <price>39.00</price>
  23:   </book>
  24:   <book Type="必修課" ISBN="7-111-19149-6">
  25:     <title>算法設計與分析</title>
  26:     <author>王紅梅</author>
  27:     <price>23.00</price>
  28:   </book>
  29:   <book Type="選修課" ISBN="7-111-19149-1">
  30:     <title>計算機操作系統</title>
  31:     <author>7-111-19149-1</author>
  32:     <price>28</price>
  33:   </book>
  34: </bookstore>

為了方便讀取,我還定義一個書的實體類,名為BookModel,具體內容如下:

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5:  
   6: namespace 使用XmlDocument
   7: {
   8:     public class BookModel
   9:     {
  10:         public BookModel()
  11:         { }
  12:         /// <summary>
  13:         /// 所對應的課程類型
  14:         /// </summary>
  15:         private string bookType;
  16:  
  17:         public string BookType
  18:         {
  19:             get { return bookType; }
  20:             set { bookType = value; }
  21:         }
  22:  
  23:         /// <summary>
  24:         /// 書所對應的ISBN號
  25:         /// </summary>
  26:         private string bookISBN;
  27:  
  28:         public string BookISBN
  29:         {
  30:             get { return bookISBN; }
  31:             set { bookISBN = value; }
  32:         }
  33:  
  34:         /// <summary>
  35:         /// 書名
  36:         /// </summary>
  37:         private string bookName;
  38:  
  39:         public string BookName
  40:         {
  41:             get { return bookName; }
  42:             set { bookName = value; }
  43:         }
  44:  
  45:         /// <summary>
  46:         /// 作者
  47:         /// </summary>
  48:         private string bookAuthor;
  49:  
  50:         public string BookAuthor
  51:         {
  52:             get { return bookAuthor; }
  53:             set { bookAuthor = value; }
  54:         }
  55:  
  56:         /// <summary>
  57:         /// 價格
  58:         /// </summary>
  59:         private double bookPrice;
  60:  
  61:         public double BookPrice
  62:         {
  63:             get { return bookPrice; }
  64:             set { bookPrice = value; }
  65:         }
  66:     }
  67: }

1.使用XmlDocument.

使用XmlDocument是一種基於文檔結構模型的方式來讀取XML文件.在XML文件中,我們可以把XML看作是由文檔聲明(Declare),元素(Element),屬性(Attribute),文本(Text)等構成的一個樹.最開始的一個結點叫作根結點,每個結點都可以有自己的子結點.得到一個結點後,可以通過一系列屬性或方法得到這個結點的值或其它的一些屬性.例如:

   1: xn 代表一個結點
   2: xn.Name;//這個結點的名稱
   3: xn.Value;//這個結點的值
   4: xn.ChildNodes;//這個結點的所有子結點
   5: xn.ParentNode;//這個結點的父結點
   6: .......
1.1 讀取所有的數據. 使用的時候,首先聲明一個XmlDocument對象,然後調用Load方法,從指定的路徑加載XML文件.
   1: XmlDocument doc = new XmlDocument();
   2: doc.Load(@"..\..\Book.xml");

然後可以通過調用SelectSingleNode得到指定的結點,通過GetAttribute得到具體的屬性值.參看下面的代碼

   1: // 得到根節點bookstore
   2: XmlNode xn = xmlDoc.SelectSingleNode("bookstore");
   3:  
   4:  
   5: // 得到根節點的所有子節點
   6: XmlNodeList xnl = xn.ChildNodes;
   7:  
   8: foreach (XmlNode xn1 in xnl)
   9: {
  10:     BookModel bookModel = new BookModel();
  11:     // 將節點轉換為元素,便於得到節點的屬性值
  12:     XmlElement xe = (XmlElement)xn1;
  13:     // 得到Type和ISBN兩個屬性的屬性值
  14:     bookModel.BookISBN = xe.GetAttribute("ISBN").ToString();
  15:     bookModel.BookType = xe.GetAttribute("Type").ToString();
  16:     // 得到Book節點的所有子節點
  17:     XmlNodeList xnl0 = xe.ChildNodes;
  18:     bookModel.BookName=xnl0.Item(0).InnerText;
  19:     bookModel.BookAuthor=xnl0.Item(1).InnerText;
  20:     bookModel.BookPrice=Convert.ToDouble(xnl0.Item(2).InnerText);
  21:     bookModeList.Add(bookModel);
  22: }
  23: dgvBookInfo.DataSource = bookModeList;

在正常情況下,上面的代碼好像沒有什麽問題,但是對於讀取上面的XML文件,則會出錯,原因就是因為我上面的XML文件裏面有註釋,大家可以參看Book.xml文件中的第三行,我隨便加的一句註釋.註釋也是一種結點類型,在沒有特別說明的情況下,會默認它也是一個結點(Node).所以在把結點轉換成元素的時候就會報錯."無法將類型為“System.Xml.XmlComment”的對象強制轉換為類型“System.Xml.XmlElement”。"

技術分享

幸虧它裏面自帶了解決辦法,那就是在讀取的時候,告訴編譯器讓它忽略掉裏面的註釋信息.修改如下:

   1: XmlDocument xmlDoc = new XmlDocument();
   2: XmlReaderSettings settings = new XmlReaderSettings();
   3: settings.IgnoreComments = true;//忽略文檔裏面的註釋
   4: XmlReader reader = XmlReader.Create(@"..\..\Book.xml", settings);
   5: xmlDoc.Load(reader);

最後讀取完畢後,記得要關掉reader.

   1: reader.Close();

這樣它就不會出現錯誤.

最後運行結果如下:

技術分享

1.2 增加一本書的信息.

向文件中添加新的數據的時候,首先也是通過XmlDocument加載整個文檔,然後通過調用SelectSingleNode方法獲得根結點,通過CreateElement方法創建元素,用CreateAttribute創建屬性,用AppendChild把當前結點掛接在其它結點上,用SetAttributeNode設置結點的屬性.具體代碼如下:

加載文件並選出要結點:

   1: XmlDocument doc = new XmlDocument();
   2: doc.Load(@"..\..\Book.xml");
   3: XmlNode root = doc.SelectSingleNode("bookstore");

創建一個結點,並設置結點的屬性:

   1: XmlElement xelKey = doc.CreateElement("book");
   2: XmlAttribute xelType = doc.CreateAttribute("Type");
   3: xelType.InnerText = "adfdsf";
   4: xelKey.SetAttributeNode(xelType);

創建子結點:

   1: XmlElement xelAuthor = doc.CreateElement("author");
   2: xelAuthor.InnerText = "dfdsa";
   3: xelKey.AppendChild(xelAuthor);
最後把book結點掛接在要結點上,並保存整個文件:
   1: root.AppendChild(xelKey);
   2: doc.Save(@"..\..\Book.xml");

用上面的方法,是向已有的文件上追加數據,如果想覆蓋原有的所有數據,可以更改一下,使用LoadXml方法:

   1: XmlDocument doc = new XmlDocument();
   2: doc.LoadXml("<bookstore></bookstore>");//用這句話,會把以前的數據全部覆蓋掉,只有你增加的數據

直接把根結點選擇出來了,後面不用SelectSingleNode方法選擇根結點,直接創建結點即可,代碼同上.

1.3 刪除某一個數據

想要刪除某一個結點,直接找到其父結點,然後調用RemoveChild方法即可,現在關鍵的問題是如何找到這個結點,上面的SelectSingleNode可以傳入一個Xpath表,我們通過書的ISBN號來找到這本書所在的結點.如下:

   1: XmlElement xe = xmlDoc.DocumentElement; // DocumentElement 獲取xml文檔對象的根XmlElement.
   2: string strPath = string.Format("/bookstore/book[@ISBN=\"{0}\"]", dgvBookInfo.CurrentRow.Cells[1].Value.ToString());
   3: XmlElement selectXe = (XmlElement)xe.SelectSingleNode(strPath);  //selectSingleNode 根據XPath表達式,獲得符合條件的第一個節點.
   4: selectXe.ParentNode.RemoveChild(selectXe);

"/bookstore/book[@ISBN=\"{0}\"]"是一個Xpath表達式,找到ISBN號為所選那一行ISBN號的那本書,有關Xpath的知識請參考:XPath 語法

1.4 修改某要條數據

修改某 條數據的話,首先也是用Xpath表達式找到所需要修改的那一個結點,然後如果是元素的話,就直接對這個元素賦值,如果是屬性的話,就用SetAttribute方法設置即可.如下:

   1: XmlElement xe = xmlDoc.DocumentElement; // DocumentElement 獲取xml文檔對象的根XmlElement.
   2: string strPath = string.Format("/bookstore/book[@ISBN=\"{0}\"]", dgvBookInfo.CurrentRow.Cells[1].Value.ToString());
   3: XmlElement selectXe = (XmlElement)xe.SelectSingleNode(strPath);  //selectSingleNode 根據XPath表達式,獲得符合條件的第一個節點.
   4: selectXe.SetAttribute("Type", dgvBookInfo.CurrentRow.Cells[0].Value.ToString());//也可以通過SetAttribute來增加一個屬性
   5: selectXe.GetElementsByTagName("title").Item(0).InnerText = dgvBookInfo.CurrentRow.Cells[2].Value.ToString();
   6: selectXe.GetElementsByTagName("author").Item(0).InnerText = dgvBookInfo.CurrentRow.Cells[3].Value.ToString();
   7: selectXe.GetElementsByTagName("price").Item(0).InnerText = dgvBookInfo.CurrentRow.Cells[4].Value.ToString();
   8: xmlDoc.Save(@"..\..\Book.xml");

2.使用XmlTextReader和XmlTextWriter

XmlTextReader和XmlTextWriter是以流的形式來讀寫XML文件.

2.1XmlTextReader

使用XmlTextReader讀取數據的時候,首先創建一個流,然後用read()方法來不斷的向下讀,根據讀取的結點的類型來進行相應的操作.如下:

   1: XmlTextReader reader = new XmlTextReader(@"..\..\Book.xml");
   2:            List<BookModel> modelList = new List<BookModel>();
   3:            BookModel model = new BookModel();
   4:            while (reader.Read())
   5:            {
   6:               
   7:                if (reader.NodeType == XmlNodeType.Element)
   8:                {
   9:                    if (reader.Name == "book")
  10:                    {
  11:                        model.BookType = reader.GetAttribute(0);
  12:                        model.BookISBN = reader.GetAttribute(1);
  13:                    }
  14:                    if (reader.Name == "title")
  15:                    {
  16:                        model.BookName=reader.ReadElementString().Trim();
  17:                    }
  18:                    if (reader.Name == "author")
  19:                    {
  20:                        model.BookAuthor = reader.ReadElementString().Trim();
  21:                    }
  22:                    if (reader.Name == "price")
  23:                    {
  24:                        model.BookPrice = Convert.ToDouble(reader.ReadElementString().Trim());
  25:                    }
  26:                }
  27:  
  28:                if (reader.NodeType == XmlNodeType.EndElement)
  29:                {
  30:                    modelList.Add(model);
  31:                    model = new BookModel();
  32:                }
  33:  
  34:                
  35:            }
  36:            modelList.RemoveAt(modelList.Count-1);
  37:            this.dgvBookInfo.DataSource = modelList;

關鍵是讀取屬性的時候,你要先知道哪一個結點具有幾個屬性,然後通過GetAttribute方法來讀取.讀取屬性還可以用另外一種方法,就是用MoveToAttribute方法.可參見下面的代碼:

   1: if (reader.Name == "book")
   2:     {
   3:         for (int i = 0; i < reader.AttributeCount; i++)
   4:         {
   5:             reader.MoveToAttribute(i);
   6:             string str = "屬性:" + reader.Name + "=" + reader.Value;
   7:         }
   8:         model.BookType = reader.GetAttribute(0);
   9:         model.BookISBN = reader.GetAttribute(1);
  10:     }

效果如下:

技術分享

2.2XmlTextWriter

XmlTextWriter寫文件的時候,默認是覆蓋以前的文件,如果此文件名不存在,它將創建此文件.首先設置一下,你要創建的XML文件格式,

   1: XmlTextWriter myXmlTextWriter = new XmlTextWriter(@"..\..\Book1.xml", null);
   2: //使用 Formatting 屬性指定希望將 XML 設定為何種格式。 這樣,子元素就可以通過使用 Indentation 和 IndentChar 屬性來縮進。
   3: myXmlTextWriter.Formatting = Formatting.Indented;

然後可以通過WriteStartElement和WriteElementString方法來創建元素,這兩者的區別就是如果有子結點的元素,那麽創建的時候就用WriteStartElement,然後去創建子元素,創建完畢後,要調用相應的WriteEndElement來告訴編譯器,創建完畢,用WriteElementString來創建單個的元素,用WriteAttributeString來創建屬性.如下:

   1: XmlTextWriter myXmlTextWriter = new XmlTextWriter(@"..\..\Book1.xml", null);
   2:            //使用 Formatting 屬性指定希望將 XML 設定為何種格式。 這樣,子元素就可以通過使用 Indentation 和 IndentChar 屬性來縮進。
   3:            myXmlTextWriter.Formatting = Formatting.Indented;
   4:  
   5:            myXmlTextWriter.WriteStartDocument(false);
   6:            myXmlTextWriter.WriteStartElement("bookstore");
   7:  
   8:            myXmlTextWriter.WriteComment("記錄書本的信息");
   9:            myXmlTextWriter.WriteStartElement("book");
  10:  
  11:            myXmlTextWriter.WriteAttributeString("Type", "選修課");
  12:            myXmlTextWriter.WriteAttributeString("ISBN", "111111111");
  13:  
  14:            myXmlTextWriter.WriteElementString("author","張三");
  15:            myXmlTextWriter.WriteElementString("title", "職業生涯規劃");
  16:            myXmlTextWriter.WriteElementString("price", "16.00");
  17:  
  18:            myXmlTextWriter.WriteEndElement();
  19:            myXmlTextWriter.WriteEndElement();
  20:  
  21:            myXmlTextWriter.Flush();
  22:            myXmlTextWriter.Close();

3.使用Linq to XML.

Linq是C#3.0中出現的一個新特性,使用它可以方便的操作許多數據源,也包括XML文件.使用Linq操作XML文件非常的方便,而且也比較簡單.下面直接看代碼,

先定義 一個方法顯示查詢出來的數據
   1: private void showInfoByElements(IEnumerable<XElement> elements)
   2:        {
   3:            List<BookModel> modelList = new List<BookModel>();
   4:            foreach (var ele in elements)
   5:            {
   6:                BookModel model = new BookModel();
   7:                model.BookAuthor = ele.Element("author").Value;
   8:                model.BookName = ele.Element("title").Value;
   9:                model.BookPrice = Convert.ToDouble(ele.Element("price").Value);
  10:                model.BookISBN=ele.Attribute("ISBN").Value;
  11:                model.BookType=ele.Attribute("Type").Value;
  12:                
  13:                modelList.Add(model);
  14:            }
  15:            dgvBookInfo.DataSource = modelList;
  16:        }

3.1讀取所有的數據

直接找到元素為book的這個結點,然後遍歷讀取所有的結果.

   1: private void btnReadAll_Click(object sender, EventArgs e)
   2:        {
   3:            XElement xe = XElement.Load(@"..\..\Book.xml");
   4:            IEnumerable<XElement> elements = from ele in xe.Elements("book")
   5:                                             select ele;
   6:            showInfoByElements(elements);
   7:        }

3.2插入一條數據

插入結點和屬性都采用new的方法,如下:
   1: private void btnInsert_Click(object sender, EventArgs e)
   2:         {
   3:             XElement xe = XElement.Load(@"..\..\Book.xml");
   4:             XElement record = new XElement(
   5:             new XElement("book",
   6:             new XAttribute("Type", "選修課"),
   7:             new XAttribute("ISBN","7-111-19149-1"),
   8:             new XElement("title", "計算機操作系統"),
   9:             new XElement("author", "7-111-19149-1"),
  10:             new XElement("price", 28.00)));
  11:             xe.Add(record);
  12:             xe.Save(@"..\..\Book.xml");
  13:             MessageBox.Show("插入成功!");
  14:             btnReadAll_Click(sender, e);
  15:         }

3.3 刪除選中的數據

首先得到選中的那一行,通過ISBN號來找到這個元素,然後用Remove方法直接刪除,如下:

   1: private void btnDelete_Click(object sender, EventArgs e)
   2:        {
   3:            if (dgvBookInfo.CurrentRow != null)
   4:            {
   5:                //dgvBookInfo.CurrentRow.Cells[1]對應著ISBN號
   6:                string id = dgvBookInfo.CurrentRow.Cells[1].Value.ToString();
   7:                XElement xe = XElement.Load(@"..\..\Book.xml");
   8:                IEnumerable<XElement> elements = from ele in xe.Elements("book")
   9:                                                 where (string)ele.Attribute("ISBN") == id
  10:                                                 select ele;
  12:                {
  11:                if (elements.Count() > 0)
  13:                    elements.First().Remove();
  14:                }
  15:                xe.Save(@"..\..\Book.xml");
  16:                MessageBox.Show("刪除成功!");
  17:                btnReadAll_Click(sender, e);
  18:  
  19:            }
  20:        }

3.4 刪除所有的數據

與上面的類似,選出所有的數據,然後用Remove方法,如下:

   1: private void btnDeleteAll_Click(object sender, EventArgs e)
   2:        {
   3:            XElement xe = XElement.Load(@"..\..\Book.xml");
   4:            IEnumerable<XElement> elements = from ele in xe.Elements("book")
   5:                                             select ele;
   6:            if (elements.Count() > 0)
   7:            {
   8:                elements.Remove();
   9:            }
  10:            xe.Save(@"..\..\Book.xml");
  11:            MessageBox.Show("刪除成功!");
  12:            btnReadAll_Click(sender, e);
  13:        }

3.5 修改某一記錄

首先得到所要修改的某一個結點,然後用SetAttributeValue來修改屬性,用ReplaceNodes來修改結點元素。如下:

   1: private void btnSave_Click(object sender, EventArgs e)
   2: {
   3:     XElement xe = XElement.Load(@"..\..\Book.xml");
   4:     if (dgvBookInfo.CurrentRow != null)
   5:     {
   6:         //dgvBookInfo.CurrentRow.Cells[1]對應著ISBN號
   7:         string id = dgvBookInfo.CurrentRow.Cells[1].Value.ToString();
   8:         IEnumerable<XElement> element = from ele in xe.Elements("book")
   9:                                         where ele.Attribute("ISBN").Value == id
  10:                                         select ele;
  11:         if (element.Count() > 0)
  12:         {
  13:             XElement first = element.First();
  14:             ///設置新的屬性
  15:             first.SetAttributeValue("Type", dgvBookInfo.CurrentRow.Cells[0].Value.ToString());
  16:             ///替換新的節點
  17:             first.ReplaceNodes(
  18:                      new XElement("title", dgvBookInfo.CurrentRow.Cells[2].Value.ToString()),  
  19:                      new XElement("author", dgvBookInfo.CurrentRow.Cells[3].Value.ToString()),
  20:                      new XElement("price", (double)dgvBookInfo.CurrentRow.Cells[4].Value) 
  21:                      );
  22:         }
  23:         xe.Save(@"..\..\Book.xml");
  24:  
  25:         MessageBox.Show("修改成功!");
  26:         btnReadAll_Click(sender, e);
  27:     }
  28: }

最終效果如下:

技術分享

有關Linq to XML的知識大家可以參考LINQ國人首創LINQ專著——《精通LINQ數據訪問技術》

這次就寫到這了,我個人也在學習,所以如果大家發現錯誤,敬請批評指正,共同學習。

源碼

C#學習筆記(12)——三種方法操作XML