XML文件是一種經常使用的文件格式,例如WinForm裏面的app.config以及Web程序中的web.config文件,還有許多重要的場所都有它的身影。Xml是Internet環境中跨平臺的,依賴於內容的技術,是當前處理結構化文檔信息的有力工具。XML是一種簡單的數據存儲語言,使用一系列簡單的標記描述數據,而這些標記能夠用方便的方式創建,雖然XML佔用的空間比二進制數據要佔用更多的空間,但XML極其簡單易於掌握和使用。微軟也提供了一系列類庫來倒幫助咱們在應用程序中存儲XML文件。html
「在程序中訪問進而操做XML文件通常有兩種模型,分別是使用DOM(文檔對象模型)和流模型,使用DOM的好處在於它容許編輯和更新XML文檔,能夠隨機訪問文檔中的數據,可使用XPath查詢,可是,DOM的缺點在於它須要一次性的加載整個文檔到內存中,對於大型的文檔,這會形成資源問題。流模型很好的解決了這個問題,由於它對XML文件的訪問採用的是流的概念,也就是說,任什麼時候候在內存中只有當前節點,但它也有它的不足,它是隻讀的,僅向前的,不能在文檔中執行向後導航操做。」具體參見在Visual C#中使用XML指南之讀取XMLweb
下面我將介紹三種經常使用的讀取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,具體內容以下:app
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)等構成的一個樹.最開始的一個結點叫做根結點,每一個結點均可以有本身的子結點.獲得一個結點後,能夠經過一系列屬性或方法獲得這個結點的值或其它的一些屬性.例如:this
1: xn 表明一個結點
2: xn.Name;//這個結點的名稱
3: xn.Value;//這個結點的值
4: xn.ChildNodes;//這個結點的全部子結點
5: xn.ParentNode;//這個結點的父結點
6: .......
1: XmlDocument doc = new XmlDocument();
2: doc.Load(@"..\..\Book.xml");
而後能夠經過調用SelectSingleNode獲得指定的結點,經過GetAttribute獲得具體的屬性值.參看下面的代碼spa
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);
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插入一條數據
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: }
最終效果以下: