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

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

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());
        ///替换新的节点
        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#读取xml文件,c#,读取xml文件,读取xml文件内容

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持ASPKU。


注:相关教程知识阅读请移步到c#教程频道。