LINQ to XML 是一种启用了 LINQ 的内存 XML 编程接口,使用它可以在 .NET Framework 编程语言中处理 XML。它将 XML 文档置于内存中,可以查询和修改 XML 文档,对比传统的查询方法简便了很多
using System;
using System.Linq.Expressions;
using System.Xml.Linq;
using System.Linq;
namespace 表达式树
{
class Program
{
//初始化XML数据
public static string Xmlstrin = @"<?xml version='1.0' encoding='utf-8'?>
<Items>
<Item>
<Id>1</Id>
<Name>小李</Name>
<Description>Test1</Description>
<Item>
<Id>小王</Id>
<Name>Name1.1</Name>
<Description>Test1.1</Description>
</Item>
</Item>
<Item>
<Id>2</Id>
<Name>小张</Name>
<Description>Test2</Description>
</Item>
</Items>";
//使用LINQ来对XML文件进行查询
static void Main(string[] args)
{
//导入XML
XElement xmlDoc = XElement.Parse(Xmlstrin);
//创建查询,获取姓名为“小李”的元素
var queryResults = from item in xmlDoc.Elements("Item")
where item.Element("Name").Value == "小李"
select item;
foreach(var item in queryResults)
{
Console.WriteLine("姓名为:{0} ID为 : {1} ", item.Element("Name").Value, item.Element("Id").Value);
}
Console.Read();
}
}
}
using System;
using System.Linq.Expressions;
using System.Xml.Linq;
using System.Linq;
namespace 表达式树
{
class Program
{
//初始化XML数据
public static string Xmlstrin = @"<?xml version='1.0' encoding='utf-8'?>
<Items>
<Item>
<Id>1</Id>
<Name>小李</Name>
<Description>Test1</Description>
<Item>
<Id>小王</Id>
<Name>Name1.1</Name>
<Description>Test1.1</Description>
</Item>
</Item>
<Item>
<Id>2</Id>
<Name>小张</Name>
<Description>Test2</Description>
</Item>
</Items>";
//使用LINQ来对XML文件进行查询
static void Main(string[] args)
{
//导入XML
XElement xmlDoc = XElement.Parse(Xmlstrin);
//创建查询,获取姓名为“小李”的元素
var queryResults = from item in xmlDoc.Elements("Item")
where item.Element("Name").Value == "小李"
select item;
foreach(var item in queryResults)
{
Console.WriteLine("姓名为:{0} ID为 : {1} ", item.Element("Name").Value, item.Element("Id").Value);
}
Console.Read();
}
}
}