C# LINQ to XML

W3C制定了XML DOM标准,.Net为了支持W3C的标准,从1.1版本开始就引入了XmlDocument类。我在前一篇博客中,介绍了如何使用XmlDocument类来对XML文档进行操作。后来 .Net又引入了LINQ,于是LINQ to XML也就应运而生,所以在.Net中,不仅可以用W3C XML DOM标准,还可以使用LINQ to XML来操作XML文档。下面就来简单介绍一下如何使用LINQ to XML。

(一) 加载

加载XML比较常用的有三种方法:

public static XDocument Load(string uri);public static XDocument Load(Stream stream);public static XDocument Parse(string text);

下面代码演示如何使用它们:

// public static XDocument Load(string uri);
// uri 即为要装载的文件名
var doc1 = XDocument.Load("XMLFile1.xml"); // public static XDocument Load(Stream stream);
Entity retrievedAnnotation = _orgService.Retrieve("annotation" , new Guid("C1B13C7F-F430-E211-8FA1-984BE1731399"), new ColumnSet(true));
byte[] fileContent = Convert.FromBase64String(retrievedAnnotation["documentbody"].ToString());
MemoryStream ms = new MemoryStream(fileContent);
XDocument xDoc = XDocument.Load(ms); // public static XDocument Parse(string text);
string str = @"<Customers><Customer id='01' city='Beijing' country='China' name='Lenovo'/></Customers>";
var doc2 = XDocument.Parse(str); 

(二) 查询

我们以下面的XML文档为例:

<?xml version="1.0" encoding="utf-8" ?>
<Customers> <Customer id="01" city="Beijing" country="China">Lenovo <Order OrderID="1001" Freight="36.00" /> <Order OrderID="1003" Freight="61.50" /> </Customer> <Customer id="02" city="Amsterdam" country="The Netherlands">Shell <Order OrderID="1002" Freight="56.65" /> <Order OrderID="1004" Freight="65.50" /> <Order OrderID="1005" Freight="100.50" /> </Customer>
</Customers>

1. 返回所有Customer 节点:

var result = from customer in doc1.Descendants("Customer") select customer.Value;
foreach (var s in result)
{ Console.WriteLine(s);
}

输出结果:

Lenovo

Shell

2. 返回id为02并且 city 为 Amsterdam 的customer :

var result = (from customer in doc1.Descendants("Customer") where (string)customer.Attribute("id") == "02" && (string)customer.Attribute("city") == "Amsterdam" select customer.Value).FirstOrDefault();
Console.WriteLine(result); 

输出结果:

Shell

3. 查找出 order ID 1003的customer ID和它的freight:

var result = (from order in doc1.Descendants("Order") where order.Attribute("OrderID").Value == "1003" select new { CustomerID = order.Parent.Attribute("id").Value,                            Freight = (decimal)order.Attribute("Freight") }).FirstOrDefault();
Console.WriteLine(string.Format("Customer ID: {0} Freight: {1}", result.CustomerID, result.Freight));

输出结果:

Customer ID: 01 Freight: 61.50

4. 查询每个客户的freight的总和

var result = from customer in doc1.Descendants("Customer") select new { CustomerName = customer.Value, TotalFreight = customer.Descendants("Order").Sum(o => (decimal)o.Attribute("Freight")) };
foreach (var r in result)
{ Console.WriteLine(string.Format("Customer: {0} Total Freight: {1}", r.CustomerName, r.TotalFreight));
} 

输出结果:

Customer: Lenovo Total Freight: 97.50 
Customer: Shell Total Freight: 222.65

5. 使用LINQ to XML Join

Join可以用在LINQ to XML和其他的LINQ providers,比如说LINQ to Objects。下面的代码展示了如何将一个数组和一个XML文件Join起来。

string[] orders = {"1001", "2000", "1002"};
var result = from order in doc1.Descendants("Order") join selected in orders on (string)order.Attribute("OrderID") equals selected select new { CustomerName = order.Parent.Value, OrderID = selected, Freight = (decimal)(order.Attribute("Freight")) };
foreach (var r in result)
{ Console.WriteLine(string.Format("Customer ID: {0} Order:{1} Freight: {2}", r.CustomerName, r.OrderID, r.Freight));
}

输出结果:

Customer ID: Lenovo Order:1001 Freight: 36,00 
Customer ID: Shell Order:1002 Freight: 56,65

(三) 创建

以创建以下XML文档为例:

<?xml version="1.0" encoding="utf-8"?>
<Customers> <Customer id="01" city="Beijing" country="China" name="Lenovo"> <Order OrderID="1001" Freight="36.00" /> </Customer>
</Customers>

var doc = new XDocument( new XElement("Customers", new XElement("Customer", new XAttribute("id", "01"), new XAttribute("city", "Beijing"), new XAttribute("country", "China"), new XAttribute("name", "Lenovo"), new XElement("Order", new XAttribute("OrderID", "1001"), new XAttribute("Freight", "36.00") ) ) )
);doc.Save("test.xml"); 

(四) 更改

以下面的XML文档为例

<?xml version="1.0" encoding="utf-8" ?>
<Customers> <Customer id="01" city="Beijing" country="China" name="Lenovo"> <Contact gender="female" title="Support">Li Li</Contact> </Customer> <Customer id="02" city="Amsterdam" country="The Netherlands" name="Shell"> <Contact gender="male" title="Sales Person">Aaron Babbitt</Contact> <Contact gender="female" title="Sales Manager">Daisy Cabell</Contact> <Contact gender="male" title="Sales Person">Gabriel Eads</Contact> </Customer>
</Customers>

1. 将Contact Li Li更改为Evi

var node = (from x in doc1.Descendants("Contact")where x.Value == "Li Li"select x).FirstOrDefault();
node.Value = "Evi";

2. 将id为02的Customer的city属性更改为Den Haag

var node = (from x in doc1.Descendants("Customer")where x.Attribute("id").Value == "02"select x).FirstOrDefault();
node.Attribute("city").Value = "Den Haag";

3. 将id为02的Customer的所有下属Contact的title属性更改为Functional Consultant

var node = (from x in doc1.Descendants("Customer")where x.Attribute("id").Value == "02"select x).FirstOrDefault();
var nodelist = from x in node.Descendants("Contact")select x;
nodelist.ToList().ForEach(x => x.Attribute("title").Value = "Functional Consultant");

(五) 删除节点

还以下面的XML文档为例

<?xml version="1.0" encoding="utf-8" ?>
<Customers> <Customer id="01" city="Beijing" country="China" name="Lenovo"> <Contact gender="female" title="Support">Li Li</Contact> </Customer> <Customer id="02" city="Amsterdam" country="The Netherlands" name="Shell"> <Contact gender="male" title="Sales Person">Aaron Babbitt</Contact> <Contact gender="female" title="Sales Manager">Daisy Cabell</Contact> <Contact gender="male" title="Sales Person">Gabriel Eads</Contact> </Customer>
</Customers>

1. 删除Contact Li Li节点

var node = (from x in doc1.Descendants("Contact")where x.Value == "Li Li"select x).FirstOrDefault();
node.Remove();

结果:

<?xml version="1.0" encoding="utf-8"?>
<Customers><Customer id="01" city="Beijing" country="China" name="Lenovo" /><Customer id="02" city="Amsterdam" country="The Netherlands" name="Shell"><Contact gender="male" title="Sales Person">Aaron Babbitt</Contact><Contact gender="female" title="Sales Manager">Daisy Cabell</Contact><Contact gender="male" title="Sales Person">Gabriel Eads</Contact></Customer>
</Customers>

2. 删除Contact Li Li节点的父节点

var node = (from x in doc1.Descendants("Contact")where x.Value == "Li Li"select x).FirstOrDefault();
node.Parent.Remove();

结果:

<?xml version="1.0" encoding="utf-8"?>
<Customers><Customer id="02" city="Amsterdam" country="The Netherlands" name="Shell"><Contact gender="male" title="Sales Person">Aaron Babbitt</Contact><Contact gender="female" title="Sales Manager">Daisy Cabell</Contact><Contact gender="male" title="Sales Person">Gabriel Eads</Contact></Customer>
</Customers>

(六) Namespace

<?xml version="1.0" encoding="utf-8" ?>
<root xmlns:h="http://www.w3.org/TR/html4/"xmlns:f="http://www.w3schools.com/furniture"><h:table><h:tr><h:td>Apples</h:td><h:td>Bananas</h:td></h:tr></h:table><f:table><f:name>African Coffee Table</f:name><f:width>80</f:width><f:length>120</f:length></f:table>
</root>

查询上面文档的第一个f:name节点

string f = @"http://www.w3schools.com/furniture";
var node = (from x in doc1.Descendants(XNamespace.Get(f) + "name")                        select x).FirstOrDefault();
Console.WriteLine(node.Value);

总结:

1. XDocument提供了对XML文档在内存中的随机的读写操作。 
2. XDocument使用LINQ to XML来读取XML结点。 
3. 你可以通过LINQ投射(projection)来将XML变换为Object。 
4. LINQ投射可以将XML变换为IEnumerable<String>。 
5. LINQ投射可以将XML变换为其他格式的XML。

C# LINQ to XML相关推荐

  1. LINQ to XML 建立,读取,增,删,改

    LINQ to XML的出现使得我们再也不需要使用XMLDocument这样复杂的一个个的没有层次感的添加和删除.LINQ可以使的生成的XML文档在内存中错落有致.下面以一个小的例子说名LINQ to ...

  2. Linq初级班 Linq To XML体验(基础篇)

    LINQ To XML体验(基础) 这两天开始学习LINQ to XML的知识,我会继续把自己的感想和示例发布给初学者们学习的,一样欢迎高手们多多指点,请勿使用过激语言,针锋相对,我是个初学者,自知还 ...

  3. LINQ之路19:LINQ to XML之X-DOM更新、和Value属性交互

    本篇包含两部分内容:X-DOM更新一节中我们会详细讨论LINQ to XML的更新方式,包括Value的更新.子节点和属性的更新.通过Parent节点实现更新: 和Value属性交互一节会详细讨论XE ...

  4. LINQ to XML 常用操作(转)

    查找具有特定属性的元素 XElement root = XElement.Load("PurchaseOrder.xml"); IEnumerable<XElement> ...

  5. Linq To Xml学习 - 1.LINQ to XML 概述

    LINQ to XML 是一种启用了 LINQ 的内存 XML 编程接口,使用它,可以在 .NET Framework 编程语言中处理 XML. 它将 XML 文档置于内存中,这一点很像文档对象模型 ...

  6. [Linq]Linq To Xml (待整理)

    [Linq]Linq To Xml (待整理) Linq To Xml (待整理) posted on 2012-02-28 10:38 水墨.MR.H 阅读(...) 评论(...) 编辑 收藏 转 ...

  7. LINQ to XML .Net 3.5 中的新XML对象

    System.Xml.Linq 命名空间中,有一系列新的LINQ to XML 帮助对象,使处理内存中的XML文档变的非常简单. 示例使用的Hamlet.xml来源自C#高级编程源代码. XDocum ...

  8. 24.C#LINQ TO XML(十二章12.3)

    自己也写了那么多,但还有很多不懂,有点浮躁吧,但饭还是要吃啊,说说LINQ TO XML吧. LINQ TO XML位于System.Xml.Linq程序集,并且大多数类型位于System.Xml.L ...

  9. 用linq查询html中div个数,C#使用Linq to XML进行XPath查询

    最近在用到HtmlAgliltyPack进行结点查询时,发现这里选择结点使用的是XPath.所以这里总结一下在C#中使用XPath查询XML的方式.习惯了用Linq,这里也是用的Linq to xml ...

  10. 一个简单的LINQ TO XML, AJAX 例子[译]

    这个教程是用Visual Studio.net 2008建立,也可以使用VS2005,但你需要从这里下载安装Microsoft's ASP.NET AJAX Extensions,AJAX和LINQ是 ...

最新文章

  1. opencv线性滤波(滤波与模糊的区别)
  2. WinForm中给DataGridView添加 自动编号
  3. nginx 配置详解
  4. java random算法_负载均衡--随机算法(Random)
  5. 【HDU - 1302】The Snail (模拟,水题)
  6. js ‘use strict’详解
  7. [转载] JAVA面向对象之代码块 继承 方法的重写 super关键字与重写toString()方法介绍
  8. (转载)—— Logistic Regression(逻辑回归)模型实现二分类和多分类
  9. python模块介绍-asyncore 异步socket处理器
  10. html设置桌面背景win7,怎么让电脑桌面背景动起来 win7设置动态背景桌面的方法...
  11. Java方法 根据经纬度计算距离
  12. 牛学长周年庆活动:软件大促限时抢,注册码免费送!
  13. vant 中 van-address-edit地址编辑 地址回显获取 areaCode
  14. 教你如何优秀的选择付费代理ip的提供商
  15. 重新安装的nvidia显卡驱动
  16. 空间存储公链(SSCC)主链已进入公测阶段预计2020年初上线
  17. 机器学习 K近邻之KD树基本概念、绘制KD树
  18. 2020中国高校计算机大赛网络技术挑战赛,【科研竞赛】2020年度“中国高校计算机大赛-网络技术挑战赛”...
  19. 如何使用码云高校版布置小组作业? | 码云高校版最佳实践
  20. three.js流动线

热门文章

  1. Spring Cloud Config Server
  2. 潘在亮:给业务开发提供黑科技装备的“测试Q博士”
  3. C#枚举类型的常用操作总结
  4. 迷你MVVM框架 avalonjs 学习教程20、路由系统
  5. 流之过滤器流(将过滤器串链在一起)
  6. Linux中文件查找技术大全
  7. 初识 npm script : 用 npm init 快速创建项目
  8. TypeScript 安装与使用
  9. MiniO对象存储服务 磁盘缓存快速入门 ​​​​​​​
  10. 安装Debian-9(Stretch)服务器图文教程