LINQ to XML 笔记,确实比DOM好用,方便。

用过Linq to sql, 用过Linq to object,都很震撼,却还没用过Linq to xml和Linq to dataset,这两天有幸用了两下Linq to xml,感觉还真的是挺方便,好用。

写正文之前,先回顾总结一下.net里操作xml文件的方法,虽然没有java中的左一个api,右一个框架,但.net中这些年也是积累了几种常用的操作xml的方法, 如下:

1.最土的是使用XmlTextReader 按文本方式读取,用XmlTextWriter写。
2.以前最常用的是使用XmlDocument的DOM技术。
  XmlDocument doc=new XmlDocument();
  doc.Load(Server.MapPath("student.xml"));

3.再有就是最新的Linq to xml了。


Baidu百科里说,LINQ to XML 与 DOM 不同: 它提供一种新的对象模型,这是一种更轻量的模型,使用也更方便。

我感觉所言非虚,看如下代码片段:

首先要确保: using System.Xml.Linq;

1.加载,修改,保存xml文件

XElement xmlRoot = XElement.Load(this.txtFile.Text);
if (xmlRoot != null)
{
    string trueName = "";
    foreach (XElement element in xmlRoot.Elements("data"))
    {
        trueName = (string)element.Attribute("RealName");

        if (realName != "")
        {
           element.SetAttributeValue("name", realName);
        }
    }
    xmlRoot.Save(this.txtFile.Text);
}

2.加载,循环遍历xml文件

XDocument xDoc = XDocument.Parse(xmlString); //xmlString: 一个xml字符串
XElement XmlRoot = xDoc.Root
if (XmlRoot != null)
{
  foreach (XElement element in XmlRoot.Elements("Student"))
  {
    string StudentID = (string)element.Element("StudentID");
    string StudentName = (string)element.Element("StudentName");
  }
}

之后再补上查询的例子。


推荐资料:

.net读取XML文件的几种方法
http://www.si9o.com/b/ct/2010/10/435831773.htm

原文地址:https://www.cnblogs.com/liuzhendong/p/2547148.html