详解c#读取XML的实例代码

2019-12-30 15:24:36刘景俊

先定义 一个方法显示查询出来的数据


  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);
   
        }
      }