欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網!

C#教程

當前位置:主頁 > 軟件編程 > C#教程 >

詳解c#讀取XML的實例代碼

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C#教程|點擊: 次

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

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

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

1: 使用 XmlDocument

2: 使用 XmlTextReader

3: 使用 Linq to Xml

這里我先創(chuàng)建一個XML文件,名為Book.xml下面所有的方法都是基于這個XML文件的,文件內容如下:

 <?xml version="1.0" encoding="utf-8"?>
   <bookstore>
    <!--記錄書本的信息-->
    <book Type="必修課" ISBN="7-111-19149-2">
     <title>數據結構</title>
     <author>嚴蔚敏</author>
     <price>30.00</price>
    </book>
    <book Type="必修課" ISBN="7-111-19149-3">
    <title>路由型與交換型互聯網基礎</title>
    <author>程慶梅</author>
    <price>27.00</price>
   </book>
   <book Type="必修課" ISBN="7-111-19149-4">
    <title>計算機硬件技術基礎</title>
    <author>李繼燦</author>
    <price>25.00</price>
   </book>
   <book Type="必修課" ISBN="7-111-19149-5">
    <title>軟件質量保證與管理</title>
    <author>朱少民</author>
    <price>39.00</price>
   </book>
   <book Type="必修課" ISBN="7-111-19149-6">
    <title>算法設計與分析</title>
    <author>王紅梅</author>
    <price>23.00</price>
   </book>
   <book Type="選修課" ISBN="7-111-19149-1">
    <title>計算機操作系統</title>
    <author>7-111-19149-1</author>
    <price>28</price>
   </book>
  </bookstore>

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

 using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Text;
   
   namespace 使用XmlDocument
   {
     public class BookModel
     {
      public BookModel()
      { }
      /// <summary>
      /// 所對應的課程類型
      /// </summary>
      private string bookType;
   
      public string BookType
      {
        get { return bookType; }
        set { bookType = value; }
      }
   
      /// <summary>
      /// 書所對應的ISBN號
      /// </summary>
      private string bookISBN;
   
      public string BookISBN
      {
        get { return bookISBN; }
        set { bookISBN = value; }
      }
   
      /// <summary>
      /// 書名
      /// </summary>
      private string bookName;
   
      public string BookName
      {
        get { return bookName; }
        set { bookName = value; }
      }
   
      /// <summary>
      /// 作者
      /// </summary>
      private string bookAuthor;
   
      public string BookAuthor
      {
        get { return bookAuthor; }
        set { bookAuthor = value; }
      }
   
      /// <summary>
      /// 價格
      /// </summary>
      private double bookPrice;
   
      public double BookPrice
      {
        get { return bookPrice; }
        set { bookPrice = value; }
      }
    }
  }

1.使用XmlDocument.

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

  xn 代表一個結點
   xn.Name;//這個結點的名稱
   xn.Value;//這個結點的值
   xn.ChildNodes;//這個結點的所有子結點
   xn.ParentNode;//這個結點的父結點
   .......

1.1 讀取所有的數據.

使用的時候,首先聲明一個XmlDocument對象,然后調用Load方法,從指定的路徑加載XML文件.

XmlDocument doc = new XmlDocument();
doc.Load(@"..\..\Book.xml");

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

  // 得到根節(jié)點bookstore
   XmlNode xn = xmlDoc.SelectSingleNode("bookstore");
   
   
   // 得到根節(jié)點的所有子節(jié)點
   XmlNodeList xnl = xn.ChildNodes;
   
   foreach (XmlNode xn1 in xnl)
   {
    BookModel bookModel = new BookModel();
    // 將節(jié)點轉換為元素,便于得到節(jié)點的屬性值
    XmlElement xe = (XmlElement)xn1;
    // 得到Type和ISBN兩個屬性的屬性值
    bookModel.BookISBN = xe.GetAttribute("ISBN").ToString();
    bookModel.BookType = xe.GetAttribute("Type").ToString();
    // 得到Book節(jié)點的所有子節(jié)點
    XmlNodeList xnl0 = xe.ChildNodes;
    bookModel.BookName=xnl0.Item(0).InnerText;
    bookModel.BookAuthor=xnl0.Item(1).InnerText;
    bookModel.BookPrice=Convert.ToDouble(xnl0.Item(2).InnerText);
    bookModeList.Add(bookModel);
  }
  dgvBookInfo.DataSource = bookModeList;

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

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

XmlDocument xmlDoc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;//忽略文檔里面的注釋
XmlReader reader = XmlReader.Create(@"..\..\Book.xml", settings);
xmlDoc.Load(reader);

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

 reader.Close();

這樣它就不會出現錯誤.

最后運行結果如下:

1.2 增加一本書的信息.

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

加載文件并選出要結點:

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

創(chuàng)建一個結點,并設置結點的屬性:

  XmlElement xelKey = doc.CreateElement("book");
   XmlAttribute xelType = doc.CreateAttribute("Type");
   xelType.InnerText = "adfdsf";
   xelKey.SetAttributeNode(xelType);

創(chuàng)建子結點:

  XmlElement xelAuthor = doc.CreateElement("author");
   xelAuthor.InnerText = "dfdsa";
   xelKey.AppendChild(xelAuthor);

最后把book結點掛接在要結點上,并保存整個文件:

root.AppendChild(xelKey);
doc.Save(@"..\..\Book.xml");

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

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

直接把根結點選擇出來了,后面不用SelectSingleNode方法選擇根結點,直接創(chuàng)建結點即可,代碼同上.

1.3 刪除某一個數據

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

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

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

1.4 修改某要條數據

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

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

2.使用XmlTextReader和XmlTextWriter

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

2.1XmlTextReader

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

   

 XmlTextReader reader = new XmlTextReader(@"..\..\Book.xml");
        List<BookModel> modelList = new List<BookModel>();
        BookModel model = new BookModel();
        while (reader.Read())
        {
          
          if (reader.NodeType == XmlNodeType.Element)
          {
            if (reader.Name == "book")
            {
              model.BookType = reader.GetAttribute(0);
              model.BookISBN = reader.GetAttribute(1);
            }
            if (reader.Name == "title")
            {
              model.BookName=reader.ReadElementString().Trim();
            }
            if (reader.Name == "author")
            {
              model.BookAuthor = reader.ReadElementString().Trim();
            }
            if (reader.Name == "price")
            {
              model.BookPrice = Convert.ToDouble(reader.ReadElementString().Trim());
            }
          }
   
          if (reader.NodeType == XmlNodeType.EndElement)
          {
            modelList.Add(model);
            model = new BookModel();
          }
   
          
        }
        modelList.RemoveAt(modelList.Count-1);
        this.dgvBookInfo.DataSource = modelList;

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

  if (reader.Name == "book")
     {
       for (int i = 0; i < reader.AttributeCount; i++)
       {
         reader.MoveToAttribute(i);
         string str = "屬性:" + reader.Name + "=" + reader.Value;
       }
       model.BookType = reader.GetAttribute(0);
       model.BookISBN = reader.GetAttribute(1);
    }

效果如下:

2.2XmlTextWriter

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

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

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

  XmlTextWriter myXmlTextWriter = new XmlTextWriter(@"..\..\Book1.xml", null);
        //使用 Formatting 屬性指定希望將 XML 設定為何種格式。 這樣,子元素就可以通過使用 Indentation 和 IndentChar 屬性來縮進。
        myXmlTextWriter.Formatting = Formatting.Indented;
   
        myXmlTextWriter.WriteStartDocument(false);
        myXmlTextWriter.WriteStartElement("bookstore");
   
        myXmlTextWriter.WriteComment("記錄書本的信息");
        myXmlTextWriter.WriteStartElement("book");
   
        myXmlTextWriter.WriteAttributeString("Type", "選修課");
        myXmlTextWriter.WriteAttributeString("ISBN", "111111111");
   
        myXmlTextWriter.WriteElementString("author","張三");
        myXmlTextWriter.WriteElementString("title", "職業(yè)生涯規(guī)劃");
        myXmlTextWriter.WriteElementString("price", "16.00");
   
        myXmlTextWriter.WriteEndElement();
        myXmlTextWriter.WriteEndElement();
   
        myXmlTextWriter.Flush();
        myXmlTextWriter.Close();

3.使用Linq to XML.

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

先定義 一個方法顯示查詢出來的數據

  private void showInfoByElements(IEnumerable<XElement> elements)
      {
        List<BookModel> modelList = new List<BookModel>();
        foreach (var ele in elements)
        {
          BookModel model = new BookModel();
          model.BookAuthor = ele.Element("author").Value;
          model.BookName = ele.Element("title").Value;
          model.BookPrice = Convert.ToDouble(ele.Element("price").Value);
          model.BookISBN=ele.Attribute("ISBN").Value;
          model.BookType=ele.Attribute("Type").Value;
          
          modelList.Add(model);
        }
        dgvBookInfo.DataSource = modelList;
      }

3.1讀取所有的數據

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

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

3.2插入一條數據

插入結點和屬性都采用new的方法,如下:

  private void btnInsert_Click(object sender, EventArgs e)
       {
         XElement xe = XElement.Load(@"..\..\Book.xml");
         XElement record = new XElement(
         new XElement("book",
         new XAttribute("Type", "選修課"),
         new XAttribute("ISBN","7-111-19149-1"),
         new XElement("title", "計算機操作系統"),
         new XElement("author", "7-111-19149-1"),
        new XElement("price", 28.00)));
        xe.Add(record);
        xe.Save(@"..\..\Book.xml");
        MessageBox.Show("插入成功!");
        btnReadAll_Click(sender, e);
      }

3.3 刪除選中的數據

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

  private void btnDelete_Click(object sender, EventArgs e)
      {
        if (dgvBookInfo.CurrentRow != null)
        {
          //dgvBookInfo.CurrentRow.Cells[1]對應著ISBN號
          string id = dgvBookInfo.CurrentRow.Cells[1].Value.ToString();
          XElement xe = XElement.Load(@"..\..\Book.xml");
          IEnumerable<XElement> elements = from ele in xe.Elements("book")
                           where (string)ele.Attribute("ISBN") == id
                          select ele;
         {
          if (elements.Count() > 0)
            elements.First().Remove();
          }
          xe.Save(@"..\..\Book.xml");
          MessageBox.Show("刪除成功!");
          btnReadAll_Click(sender, e);
   
        }
      }

3.4 刪除所有的數據

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

  private void btnDeleteAll_Click(object sender, EventArgs e)
      {
        XElement xe = XElement.Load(@"..\..\Book.xml");
        IEnumerable<XElement> elements = from ele in xe.Elements("book")
                         select ele;
        if (elements.Count() > 0)
        {
          elements.Remove();
        }
        xe.Save(@"..\..\Book.xml");
        MessageBox.Show("刪除成功!");
        btnReadAll_Click(sender, e);
      }

3.5 修改某一記錄

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

  private void btnSave_Click(object sender, EventArgs e)
   {
     XElement xe = XElement.Load(@"..\..\Book.xml");
     if (dgvBookInfo.CurrentRow != null)
     {
       //dgvBookInfo.CurrentRow.Cells[1]對應著ISBN號
       string id = dgvBookInfo.CurrentRow.Cells[1].Value.ToString();
       IEnumerable<XElement> element = from ele in xe.Elements("book")
                       where ele.Attribute("ISBN").Value == id
                      select ele;
      if (element.Count() > 0)
      {
        XElement first = element.First();
        ///設置新的屬性
        first.SetAttributeValue("Type", dgvBookInfo.CurrentRow.Cells[0].Value.ToString());
        ///替換新的節(jié)點
        first.ReplaceNodes(
             new XElement("title", dgvBookInfo.CurrentRow.Cells[2].Value.ToString()), 
             new XElement("author", dgvBookInfo.CurrentRow.Cells[3].Value.ToString()),
             new XElement("price", (double)dgvBookInfo.CurrentRow.Cells[4].Value) 
             );
      }
      xe.Save(@"..\..\Book.xml");
   
      MessageBox.Show("修改成功!");
      btnReadAll_Click(sender, e);
    }
  }

最終效果如下:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持我們。

上一篇:C#使用讀寫鎖三行代碼簡單解決多線程并發(fā)的問題

欄    目:C#教程

下一篇:C# TextBox多行文本框的字數限制問題

本文標題:詳解c#讀取XML的實例代碼

本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/6091.html

網頁制作CMS教程網絡編程軟件編程腳本語言數據庫服務器

如果侵犯了您的權利,請與我們聯系,我們將在24小時內進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

聯系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網 版權所有