LINQ to XML LINQ学习第一篇
LINQ to XML LINQ学习第一篇
1、LINQ to XML类
![]()
以下的代码演示了如何使用LINQ to XML来快速创建一个xml:

public static void CreateDocument()
{
string path = @"d:\website";
XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Root", "root"));
xdoc.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>root</Root>
2、XElement类
XElement 类是 LINQ to XML 中的基础类之一。 它表示一个 XML 元素。 可以使用该类创建元素;更改元素内容;添加、更改或删除子元素;向元素中添加属性;或以文本格式序列化元素内容。 还可以与 System.Xml 中的其他类(例如 XmlReader、XmlWriter 和 XslCompiledTransform)进行互操作。
使用LINQ to XML创建xml文档有很多种方式,具体使用哪种方法要根据实际需要。而创建xml文档最简单、最常见的方式是使用XElement类。以下的代码演示了如何使用XElement类创建一个xml文档:

public static void CreateCategories()
{
string path = @"d:\website";
XElement root = new XElement("Categories",
new XElement("Category",
new XElement("CategoryID", Guid.NewGuid()),
new XElement("CategoryName", "Beverages")
),
new XElement("Category",
new XElement("CategoryID", Guid.NewGuid()),
new XElement("CategoryName", "Condiments")
),
new XElement("Category",
new XElement("CategoryID", Guid.NewGuid()),
new XElement("CategoryName", "Confections")
)
);
root.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<Categories>
<Category>
<CategoryID>57485174-46fc-4e8c-8d98-d25b53d504a1</CategoryID>
<CategoryName>Beverages</CategoryName>
</Category>
<Category>
<CategoryID>1474dde1-8014-48f7-b093-b47ca5d5b770</CategoryID>
<CategoryName>Condiments</CategoryName>
</Category>
<Category>
<CategoryID>364224e0-e002-4939-90fc-0fd93e0cf35b</CategoryID>
<CategoryName>Confections</CategoryName>
</Category>
</Categories>

XElement类包含了许多方法,这些方法使得处理xml变得轻而易举。有关这些方法请参照MSDN。
其中,Save、CreateReader、ToString和WriteTo方法是比较常用的三个方法:
![]()
3、XAttribute类
XAttribute类用来处理元素的属性,属性是与元素相关联的“名称-值”对,每个元素中不能有名称重复的属性。使用XAttribute类与使用XElement类的操作十分相似,下面的示例演示了如何在创建xml树时为其添加一个属性:

public static XElement CreateCategoriesByXAttribute()
{
XElement root = new XElement("Categories",
new XElement("Category",
new XAttribute("CategoryID", Guid.NewGuid()),
new XElement("CategoryName", "Beverages")
),
new XElement("Category",
new XAttribute("CategoryID", Guid.NewGuid()),
new XElement("CategoryName", "Condiments")
),
new XElement("Category",
new XAttribute("CategoryID", Guid.NewGuid()),
new XElement("CategoryName", "Confections")
)
);
root.Save(path);
return root;
}

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<Categories>
<Category CategoryID="a6d5ef04-3f83-4e00-aeaf-52444add7570">
<CategoryName>Beverages</CategoryName>
</Category>
<Category CategoryID="67a168d5-6b22-4d82-9bd4-67bec88c2ccb">
<CategoryName>Condiments</CategoryName>
</Category>
<Category CategoryID="17398f4e-5ef1-48da-8a72-1c54371b8e76">
<CategoryName>Confections</CategoryName>
</Category>
</Categories>

XAttribute类的方法比较少,常用的三个是:
![]()
以下的示例使用Remove来删除第一个元素的CategoryID属性:

public static void RemoveAttribute()
{
XElement xdoc = CreateCategoriesByXAttribute();
XAttribute xattr = xdoc.Element("Category").Attribute("CategoryID");
xattr.Remove();
xdoc.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<Categories>
<Category>
<CategoryName>Beverages</CategoryName>
</Category>
<Category CategoryID="5c311c1e-ede5-41e5-93f7-5d8b1d7a0346">
<CategoryName>Condiments</CategoryName>
</Category>
<Category CategoryID="bfde8db5-df84-4415-b297-cd04d8db9712">
<CategoryName>Confections</CategoryName>
</Category>
</Categories>

作为尝试,试一试以下删除属性的方法:

public static void RemoveAttributeByDoc()
{
XElement xdoc = CreateCategoriesByXAttribute();
XAttribute xattr = xdoc.Attribute("CategoryID");
xattr.Remove();
xdoc.Save(path);
}

运行该示例将会抛出一个空引用异常,因为元素Categories没有一个叫做CategoryID的属性。
4、XDocument类
XDocument类提供了处理xml文档的方法,包括声明、注释和处理指令。一个XDocument对象可以包含以下内容:
![]()
下面的示例创建了一个简单的xml文档,它包含几个元素和一个属性,以及一个处理指令和一些注释:

public static void CreateXDocument()
{
XDocument xdoc = new XDocument(
new XProcessingInstruction("xml-stylesheet", "title='EmpInfo'"),
new XComment("some comments"),
new XElement("Root",
new XElement("Employees",
new XElement("Employee",
new XAttribute("id", "1"),
new XElement("Name", "Scott Klein"),
new XElement("Title", "Geek"),
new XElement("HireDate", "02/05/2007"),
new XElement("Gender", "M")
)
)
),
new XComment("more comments")
);
xdoc.Save(path);

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet title='EmpInfo'?>
<!--some comments-->
<Root>
<Employees>
<Employee id="1">
<Name>Scott Klein</Name>
<Title>Geek</Title>
<HireDate>02/05/2007</HireDate>
<Gender>M</Gender>
</Employee>
</Employees>
</Root>
<!--more comments-->

XDocument类包含多个与XElement类相同的方法,具体内容可以参阅MSDN。需要注意的是,处理节点和元素的大部分功能都可以通过XElement获得,只有当绝对需要文档层次的处理能力,以及需要访问注释、处理指令和声明时,才有使用XDocument类的必要。
创建了xml文档后,可以使用NodesAfterSelf方法返回指定的XElement元素之后的所有同级元素。需要注意的是,此方法只包括返回集合中的同级元素,而不包括子代。此方法使用延迟执行。以下代码演示了这一过程:

public static void NodesAfterSelf()
{
XElement root = new XElement("Categories",
new XElement("Category",
new XElement("CategoryID", Guid.NewGuid()),
new XElement("CategoryName", "食品"),
new XElement("Description", "可以吃的东西")
)
);
foreach (var item in root.Element("Category").Element("CategoryID").NodesAfterSelf())
{
Console.WriteLine((item as XElement).Value);
}
}

二、LINQ to XML编程概念
本节将介绍LINQ to XML编程的相关概念,例如如何加载xml、创建全新xml、操纵xml的信息以及遍历xml文档。
1、加载已有的xml
使用LINQ to XML加载xml可以从多种数据源获得,例如字符串、XmlReader、TextReader或文件。
下面的示例演示了如何从文件中加载xml:

public static void LoadFromFile()
{
XElement root = XElement.Load(path);
Console.WriteLine(root.ToString());
}

也可以使用Parse方法从一个字符串加载xml:

public static void LoadFromString()
{
XElement root = XElement.Parse(@"
<Categories>
<Category>
<CategoryID>1</CategoryID>
<CategoryName>Beverages</CategoryName>
<Description>Soft drinks, coffees, teas, beers, and ales</Description>
</Category>
</Categories>
");
Console.WriteLine(root.ToString());
}

2、保存xml
在前面的示例中曾多次调用XElement对象的Save方法来保存xml文档,在这里就不冗述了。
3、创建xml
在前面的示例中曾多次调用XElement对象的构造函数来创建xml文档,在这里就不冗述了。需要说明的是,在使用LINQ to XML创建xml文档时,会有代码缩进,这使代码的可读性大大加强。
4、遍历xml
使用LINQ to XML在xml树中遍历xml是相当简单的。只需要使用XElement和XAttribute类中所提供的方法。Elements和Element方法提供了定位到某个或某些元素的方式。下面的示例演示了如何遍历xml树,并获取指定元素的方式:

public static void Enum()
{
XElement root = new XElement("Categories");
using (NorthwindDataContext db = new NorthwindDataContext())
{
root.Add(
db.Categories
.Select
(
c => new XElement
(
"Category"
, new XElement("CategoryName", c.CategoryName)
)
)
);
}
foreach (var item in root.Elements("Category"))
{
Console.WriteLine(item.Element("CategoryName").Value);
}
}

上述代码运行的结果为:
![]()
是不是很简单呢?Nodes()、Elements()、Element(name)和Elements(name)方法为xml树的导航提供了基本功能。
5、操纵xml
LINQ to XML一个重要的特性是能够方便地修改xml树,如添加、删除、更新和复制xml文档的内容。
I.插入
使用XNode类的插入方法可以方便地向xml树添加内容:
![]()
在下面的示例中,使用AddAfterSelf方法向现有xml中添加一个新节点:

public static void AddAfterSelf()
{
XElement root = XElement.Parse(@"
<Categories>
<Category>
<CategoryID>1</CategoryID>
<CategoryName>Beverages</CategoryName>
<Description>Soft drinks, coffees, teas, beers, and ales</Description>
</Category>
</Categories>
");
XElement xele = root.Element("Category").Element("CategoryName");
xele.AddAfterSelf(new XElement("AddDate", DateTime.Now));
root.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<Categories>
<Category>
<CategoryID>1</CategoryID>
<CategoryName>Beverages</CategoryName>
<AddDate>2010-01-31T03:08:51.813736+08:00</AddDate>
<Description>Soft drinks, coffees, teas, beers, and ales</Description>
</Category>
</Categories>

当需要添加一个元素到指定节点之前时,可以使用AddBeforeSelf方法。
II.更新
在LINQ to XML中更新xml内容可以使用以下几种方法:
![]()
在下面的示例中使用了ReplaceWith与SetElementValue方法对xml进行了更新操作:

public static void Update()
{
XElement root = XElement.Parse(@"
<Categories>
<Category>
<CategoryID>1</CategoryID>
<CategoryName>Beverages</CategoryName>
<Description>Soft drinks, coffees, teas, beers, and ales</Description>
</Category>
</Categories>
");
root.Element("Category").Element("CategoryID").ReplaceWith(new XElement("ID", "2"));
root.Element("Category").SetElementValue("CategoryName", "test data");
root.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<Categories>
<Category>
<ID>2</ID>
<CategoryName>test data</CategoryName>
<Description>Soft drinks, coffees, teas, beers, and ales</Description>
</Category>
</Categories>

III.删除
可以使用Remove(XElement)与RemoveAll方法来删除xml。
在下面的示例中,使用了RemoveAll方法:

public static void Remove()
{
string path = @"d:\";
XElement root = XElement.Parse(@"
<Categories>
<Category>
<CategoryID>1</CategoryID>
<CategoryName>Beverages</CategoryName>
<Description>Soft drinks, coffees, teas, beers, and ales</Description>
</Category>
</Categories>
");
root.RemoveAll();
root.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<Categories />

在下面的示例中,使用了Remove方法删除了xml的Description元素:

public static void Remove()
{
XElement root = XElement.Parse(@"
<Categories>
<Category>
<CategoryID>1</CategoryID>
<CategoryName>Beverages</CategoryName>
<Description>Soft drinks, coffees, teas, beers, and ales</Description>
</Category>
</Categories>
");
root.Element("Category").Element("Description").Remove();
root.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<Categories>
<Category>
<CategoryID>1</CategoryID>
<CategoryName>Beverages</CategoryName>
</Category>
</Categories>

6、处理属性
I.添加
LINQ to XML添加属性与添加元素师类似的,可以使用构造函数或者Add方法来添加属性:

public static void AddAttribute()
{
XElement root = new XElement("Categories",
new XElement("Category",
new XAttribute("CategoryID", "1"),
new XElement("CategoryName", "Beverages"),
new XElement("Description", "Soft drinks, coffees, teas, beers, and ales")
)
);
root.Element("Category").Add(new XAttribute("AddDate", DateTime.Now.ToShortDateString()));
root.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:
<?xml version="1.0" encoding="utf-8"?>
<Categories>
<Category CategoryID="1" AddDate="2010-01-31">
<CategoryName>Beverages</CategoryName>
<Description>Soft drinks, coffees, teas, beers, and ales</Description>
</Category>
</Categories>
II.检索
检索属性可以使用Attribute(name)方法:

public static void SelectAttribute()
{
XElement root = new XElement("Categories",
new XElement("Category",
new XAttribute("CategoryID", "1"),
new XElement("CategoryName", "Beverages"),
new XElement("Description", "Soft drinks, coffees, teas, beers, and ales")
)
);
XAttribute xattr = root.Element("Category").Attribute("CategoryID");
Console.WriteLine(xattr.Name);
Console.WriteLine(xattr.Value);
}

上述代码的运行结果为:
CategoryID
1
本文总结
本文介绍了LINQ to XML的编程基础,即System.Xml.Linq命名空间中的多个LINQ to XML类,这些类都是LINQ to XML的支持类,它们使得处理xml比使用其他的xml工具容易得多。在本文中,着重介绍的是XElement、XAttribute和XDocument。
LINQ to XML LINQ学习第一篇的更多相关文章
- 从.Net到Java学习第一篇——开篇
以前我常说,公司用什么技术我就学什么.可是对于java,我曾经一度以为“学java是不可能的,这辈子不可能学java的.”结果,一遇到公司转java,我就不得不跑路了,于是乎,回头一看N家公司交过社保 ...
- Java并发包下锁学习第一篇:介绍及学习安排
Java并发包下锁学习第一篇:介绍及学习安排 在Java并发编程中,实现锁的方式有两种,分别是:可以使用同步锁(synchronized关键字的锁),还有lock接口下的锁.从今天起,凯哥将带领大家一 ...
- JVM学习第一篇思考:一个Java代码是怎么运行起来的-上篇
JVM学习第一篇思考:一个Java代码是怎么运行起来的-上篇 作为一个使用Java语言开发的程序员,我们都知道,要想运行Java程序至少需要安装JRE(安装JDK也没问题).我们也知道我们Java程序 ...
- Android基础学习第一篇—Project目录结构
写在前面的话: 1. 最近在自学Android,也是边看书边写一些Demo,由于知识点越来越多,脑子越来越记不清楚,所以打算写成读书笔记,供以后查看,也算是把自己学到所理解的东西写出来,献丑,如有不对 ...
- Golang学习-第一篇 Golang的简单介绍及Windows环境下安装、部署
序言 这是本人博客园第一篇文章,写的不到位之处,希望各位看客们谅解. 本人一直从事.NET的开发工作,最近在学习Golang,所以想着之前学习的过程中都没怎么好好的将学习过程记录下来.深感惋惜! 现在 ...
- Python学习第一篇
好久没有来博客园了,今天开始写自己学习Python和Hadoop的学习笔记吧.今天写第一篇,Python学习,其他的环境部署都不说了,可以参考其他的博客. 今天根据MachineLearning里面的 ...
- ImageJ 学习第一篇
ImageJ是世界上最快的纯Java的图像处理程序.它可以过滤一个2048x2048的图像在0.1秒内(*).这是每秒40万像素!ImageJ的扩展通过使用内置的文本编辑器和Java编译器的Image ...
- Java图像处理最快技术:ImageJ 学习第一篇
ImageJ是世界上最快的纯Java的图像处理程序. 它能够过滤一个2048x2048的图像在0.1秒内(*). 这是每秒40万像素!ImageJ的扩展通过使用内置的文本编辑器和Java编译器的Ima ...
- Linq专题之提高编码效率—— 第一篇 Aggregate方法
我们知道linq是一个很古老的东西,大家也知道,自从用了linq,我们的foreach少了很多,但有一个现实就是我们在实际应用中使用到的却是屈指可数 的几个方法,这个系列我会带领大家看遍linq,好的 ...
随机推荐
- 【百度地图API】如何调整结果面板的样式?如何获取指定页码的结果?
原文:[百度地图API]如何调整结果面板的样式?如何获取指定页码的结果? 摘要: 1.你是否想自定义查询后,结果面板的显示样式? 2.数据接口每次只返回10条结果,如何取到单独每一页的结果? ---- ...
- jAVA 得到Map价值
jAVA 获取Map中的值 Map<String, String> map=new HashMap<String, String>(); map.put("name& ...
- .NET Framework 各版本区别
.NET Framework 各版本区别 .NET Framework 1.1 自1.0版本以来的改进:自带了对mobile asp .net控件的支持.这在1.0版本是以附加功能方式实现的,现在已经 ...
- 我所理解的Spring AOP的基本概念
Spring AOP中的概念晦涩难懂,读官方文档更是像读天书,看了非常多样例后,写一些自己理解的一些spring的概念.要理解面向切面编程,要首先理解代理模式和动态代理模式. 如果一个OA系统中的一个 ...
- Maven入门笔记
首先安装Maven,Maven的安装很简单,这里就不在说了. 先要确定把工程放在哪个路径下,创建一个文件夹并且在该文件夹下打开shell命令.可以先运行下面的命令,创建一个工程: mvn archet ...
- c++ 正則表達式
正則表達式是经常使用的一种方法.比較有名的类库是boost,可是这个类库在重了.全部就像找一些轻量级的类库. 后来发现准标准的库tr1已经非常方便了,微软vs2008 sp1 以上版本号都支持了.全部 ...
- .NET 开源了,Visual Studio 开始支持 Android 和 iOS 程序编写并自带 Android 模拟器
.NET 开源了,Visual Studio 开始支持 Android 和 iOS 程序编写并自带 Android 模拟器 北京时间今天凌晨的 Connect(); 大会上,多少程序员的假想成为现实. ...
- leetcode[61] Unique Paths
题目:给定一个m*n的矩阵,从头开始,只能往右边和下边走,一次走一格,知道走到最后一个(右下角)为止.总共有多少种走法. 典型的动态规划吧.其实从头走到尾部,和从尾部开始走到头是一样的次数.我们用一个 ...
- firefox 对WebRTC支持
本文原创自 http://blog.csdn.net/voipmaker 转载注明出处. firefox pc和android 最新版本号已经默认支持webrtc, 同一时候,firefox在支持V ...
- firefox os 该设备呼叫移动开发
1)话筒 权限:telephony api:navigator.moztelephony 参考链接:https://wiki.mozilla.org/WebAPI/WebTelephony 2) 扬声 ...