C#的LINQ to XML 类中使用最多的三个类:XElement、XAttribute 和 XDocument

编程入门 行业动态 更新时间:2024-10-28 10:26:11

C#的LINQ to XML 类中使用<a href=https://www.elefans.com/category/jswz/34/1771052.html style=最多的三个类:XElement、XAttribute 和 XDocument"/>

C#的LINQ to XML 类中使用最多的三个类:XElement、XAttribute 和 XDocument

目录

一、XElement 类

1.使用 XElement 类创建一个 xml 文档

(1)示例源码

(2)xml文件

2.使用LINQ to SQL或者LINQ to Object获取数据源

(1)示例源码

(2)xml文件

3.XElement 类包含的其它方法

二、XAttribute 类

1.通过 XAttribute添加属性

(1)示例源码

(2)xml文件

2.使用Remove()删除属性

(1)示例源码

(2)xml文件

3.属性不是节点 

(1)示例源码

(2)xml文件

三、XDocument 类 

1.示例

2.生成显示


        System.Xml.Linq 命名空间包含 LINQ to XML 的19个类。 LINQ to XML 是内存中的 XML 编程接口,使能轻松有效地修改 XML 文档。

        微软在 LINQ 上投入了很大的精力,使我们在编程时感觉到很舒服。处理 XML 时使用最多的三个类:XElement、XAttribute 和 XDocument。

序号说明
1Extensions包含 LINQ to XML 扩展方法。
2XAttribute表示 XML 特性。
3XCData表示包含 CDATA 的文本节点。
4XComment表示 XML 注释。
5XContainer表示可包含其他节点的节点。
6XDeclaration表示 XML 声明。
7XDocument表示 XML 文档。 有关 XDocument 对象的组件和用法,请参阅 XDocument Class Overview。
8XDocumentType表示 XML 文档类型定义 (DTD)。
9XElement表示一个 XML 元素。 有关用法信息和示例,请参阅本页的 XElement 类概述和“备注”部分。
10XName表示 XML 元素或属性的名称。
11XNamespace表示一个 XML 命名空间。 此类不能被继承。
12XNode表示 XML 树中节点的抽象概念(元素、注释、文档类型、处理指令或文本节点)。
13XNodeDocumentOrderComparer包含用于比较节点文档顺序的功能。 此类不能被继承。
14XNodeEqualityComparer比较节点以确定其是否相等。 此类不能被继承。
15XObject表示 XML 树中的节点或属性。
16XObjectChangeEventArgs提供有关 Changing 和 Changed 事件的数据。
17XProcessingInstruction表示 XML 处理指令。
18XStreamingElement表示 XML 树中支持流输出延迟的的元素。
19XText表示文本节点。

        表格中列元素详解见超链接。

一、XElement 类

        XElement 类是 LINQ to XML 中的基础类之一。 它表示一个 XML 元素。 可以使用该类创建元素;更改元素内容;添加、更改或删除子元素;向元素中添加属性;或以文本格式序列化元素内容。 还可以与System.Xml 中的其他类(例如 XmlReader、XmlWriter 和XslCompiledTransform)进行互操作。         使用 LINQ to XML 创建 xml 文档有很多种方式,具体使用哪种方法要根据实际需要。而创建 xml 文档最简单、最常见的方式是使用 XElement 类。

1.使用 XElement 类创建一个 xml 文档

(1)示例源码

//通过XElement创建XMLusing System.Xml.Linq;namespace _10_1
{class Program{static void Main(string[] args){        CreateCategories();#region 通过XElement创建XMLvoid CreateCategories(){string path = Directory.GetCurrentDirectory() + @"\People.xml";XElement root = new("Peoples",new XElement("People",new XElement("ID", Guid.NewGuid()),new XElement("Name", "王菲")),new XElement("People",new XElement("ID", Guid.NewGuid()),new XElement("Name", "谢霆锋")),new XElement("People",new XElement("ID", Guid.NewGuid()),new XElement("Name", "章子怡")),new XElement("People",new XElement("ID", Guid.NewGuid()),new XElement("Name", "汪峰")));root.Save(path);}#endregion 通过XElement创建XML}} 
}

(2)xml文件

<Peoples><People><ID>9586dab0-28a4-465a-987d-5f1e89042154</ID><Name>王菲</Name></People><People><ID>7bf22551-7635-4768-bb12-d826ba0991d3</ID><Name>谢霆锋</CategoryName></People><People><ID>bcf1f65d-38f5-40f1-8ad7-eae9d7ee117e</ID><Name>章子怡</Name></People><People><ID>dc69f99b-b8cf-46c3-bba6-a23909a199cd</ID><Name>汪峰</Name></People>
</Peoples>

2.使用LINQ to SQL或者LINQ to Object获取数据源

        LINQ to XML的强大之处还在于它可以使用LINQ to SQL或者LINQ to Object获取数据源,然后填充到xml树。

(1)示例源码

        从 Northwind 数据库中读取 Categories、Products 表中的数据来创建包含产品类别,以及每

个类别下所有产品的 xml 文件。

(2)xml文件

3.XElement 类包含的其它方法

        XElement 类包含了许多方法,这些方法使得处理 xml 变得轻而易举。其中,Save、CreateReader、ToString 和 WriteTo 方法是比较常用的三个方法:

方法参数返回值描述
CreateReaderSystem.Xml.XmlReader创建此节点的XmlReader
SayeSystem.Stringvoid将此元素序列化为文件
System.I0.TextWritervoid将此元素序列化为TextWriter
System.Xml.XmlWritervoid将此元素序列化为XmlWriter
System.String,
System.Xml.Linq.SaveOptions
void将此元素序列化为文件,并可以选择
禁用格式设置
System.IO.TextWriter
System.Xml.Linq.SaveOptions
void将此元素序列化为TextWriter,并可
以选择禁用格式设置
WriteToSystem.Xml.XmlWritervoid将此元素写入XmlWriter
ToStringSystem.String返回此节点的缩进XML
System.Xml.Ling.SaveOptionsSystem.String返回此节点的XML,并可以选择禁用
格式设置

二、XAttribute

        XAttribute 类用来处理元素的属性,属性是与元素相关联的“名称/值”对,每个元素中不能有名称重复的属性。使用 XAttribute 类与使用 XElement 类的操作十分相似。

        XAttribute 类的方法比较少,常用的三个是:

方法描述
AddAnnotation为该属性添加注解
Remove删除该属性
SetValue设定该属性的值

1.通过 XAttribute添加属性

(1)示例源码

//创建 xml 树时添加属性using System.Xml.Linq;namespace _10_1
{class Program{static void Main(string[] args){        CreateCategoriesByXAttribute();#region 创建 xml 树时添加属性XElement CreateCategoriesByXAttribute(){string path = Directory.GetCurrentDirectory() + @"\PeoplebyXAttribute.xml";XElement root = new("Peoples",new XElement("People",new XAttribute("ID", Guid.NewGuid()),new XElement("Name", "李小龙")),new XElement("People",new XAttribute("ID", Guid.NewGuid()),new XElement("Name", "李连杰")),new XElement("People",new XAttribute("ID", Guid.NewGuid()),new XElement("Name", "成龙")),new XElement("People",new XAttribute("ID", Guid.NewGuid()),new XElement("Name", "甄子丹")));root.Save(path);return root;}#endregion 创建 xml 树时添加属性}} 
}

(2)xml文件

<Peoples><People ID="ed6b428c-a188-4503-870f-d4eea12c52c4"><Name>李小龙</Name></People><People ID="40cfdf39-a189-4963-a86d-e712978c4ae7"><Name>李连杰</Name></People><People ID="d3126eb3-5ede-46f3-90a7-b1d3eb5ef627"><Name>成龙</Name></People><People ID="6558808f-9ef6-4698-b05a-9747479a5238"><Name>甄子丹</Name></People>
</Peoples>

2.使用Remove()删除属性

        使用 Remove 来删除第一个元素的ID 属性: 

(1)示例源码

using System.IO;
using System.Xml.Linq;namespace _10_1
{class Program{static void Main(string[] args){                    CreateCategoriesByXAttribute();RemoveAttribute();#region 创建 xml 树时添加属性XElement CreateCategoriesByXAttribute(){string path = Directory.GetCurrentDirectory() + @"\PeoplebyXAttribute.xml";XElement root = new("Peoples",new XElement("People",new XAttribute("ID", Guid.NewGuid()),new XElement("Name", "李小龙")),new XElement("People",new XAttribute("ID", Guid.NewGuid()),new XElement("Name", "李连杰")),new XElement("People",new XAttribute("ID", Guid.NewGuid()),new XElement("Name", "成龙")),new XElement("People",new XAttribute("ID", Guid.NewGuid()),new XElement("Name", "甄子丹")));root.Save(path);return root;}#endregion 创建 xml 树时添加属性#region 删除属性void RemoveAttribute(){string path = Directory.GetCurrentDirectory() + @"\XAttributeRemove.xml";XElement _xdoc = CreateCategoriesByXAttribute();XAttribute _attribute = _xdoc.Element("People").Attribute("ID");_attribute.Remove();_xdoc.Save(path);            }# endregion 删除属性}} 
}

(2)xml文件

         利用Element属性和Remove()方法删除第一条记录“ID”属性

<Peoples><People><Name>李小龙</Name></People><People ID="3c5d27ca-f84d-4066-b721-cfdaeee7a90b"><Name>李连杰</Name></People><People ID="dc592933-0911-4107-bc0c-ea82563781bd"><Name>成龙</Name></People><People ID="69559674-b035-4bb6-be3a-22d9b7838a45"><Name>甄子丹</Name></People>
</Peoples>

3.属性不是节点 

         XAttribute 可以构造的对象与 XElement 构造的对象一致。但属性与元素之间是有些区别的。 XAttribute 对象不是 XML 树中的节点。 它们是与 XML 元素关联的名称/值对。 与文档对象模型 (DOM) 相比,这更加贴切地反映了 XML 结构。 虽然 XAttribute 对象实际上不是 XML 树的节点,但使用 XAttribute 对象与使用 XElement 对象非常相似

(1)示例源码

using System.IO;
using System.Xml.Linq;namespace _10_1
{class Program{static void Main(string[] args){                    CreateByXAttribute();#region 通过属性创建不是节点void CreateByXAttribute(){string path = Directory.GetCurrentDirectory() + @"\CreateByXAttribute.xml";XElement _c = new("Customers",new XElement("Customer",new XElement("Name", "John Doe"),new XElement("PhoneNumbers",new XElement("Phone",new XAttribute("type", "home"),"555-555-5555"),new XElement("Phone",new XAttribute("type", "work"),"666-666-6666"))   // PhoneNumbers)       // Customer);          // CustomersConsole.WriteLine(_c);_c.Save(path);#endregion 通过属性创建不是节点}}} 
}

(2)xml文件

<Customers><Customer><Name>John Doe</Name><PhoneNumbers><Phone type="home">555-555-5555</Phone><Phone type="work">666-666-6666</Phone></PhoneNumbers></Customer>
</Customers>

三、XDocument  

        XDocument 类提供了处理 xml 文档的方法,包括声明、注释和处理指令。一个 XDocument 对象可以包含以下内容:
对象个数说明
XDeclaration一个用于指定 xml 声明中的重要组成部分,如文档编码和版本等
XElement一个指定文档的根元素
XDocumentType一个表示一个 xml DTD
XComment多个Xml 注释,将与根元素同级。
XProcessingInstruction多个为处理 xml 的应用程序指定任何所需信息

1.示例

using System.Xml.Linq;namespace _10_1
{class Program{static void Main(string[] args){        CreateXmlByXDocument();#region 通过XDocument创建XMLvoid CreateXmlByXDocument(){string path = Directory.GetCurrentDirectory() + @"\CreateXmlByXDocument.xml";XDocument _doc = new(new XComment("This is a comment."),new XProcessingInstruction("xml-stylesheet", "href='mystyle.css' title='Compact' type='text/css'"),new XElement("Pubs",new XElement("Book",new XElement("Title", "Artifacts of Roman Civilization"),new XElement("Author", "Moreno, Jordao")), //Booknew XElement("Book",new XElement("Title", "Midieval Tools and Implements"),new XElement("Author", "Gazit, Inbar"))  //Book),    //Pubsnew XComment("This is another comment.")){Declaration = new XDeclaration("1.0", "utf-8", "true")};          //newConsole.WriteLine(_doc);_doc.Save(path);}#endregion 通过XDocument创建XML}} 
}

2.生成显示

<!--This is a comment.-->
<?xml-stylesheet href='mystyle.css' title='Compact' type='text/css'?>
<Pubs><Book><Title>Artifacts of Roman Civilization</Title><Author>Moreno, Jordao</Author></Book><Book><Title>Midieval Tools and Implements</Title><Author>Gazit, Inbar</Author></Book>
</Pubs>
<!--This is another comment.-->
        XDocument 类包含多个与 XElement 类相同的方法。 处理节点和元素的大部分功能都可以通过 XElement 获得,只有当绝对需要文档层次的处理能力,以及需要访问注释、处理指令和声明时,才有使用 XDocument 类的必要。         创建了 xml 文档后,可以使用 NodesAfterSelf 方法返回指定的 XElement 元素之后的所有同级元素。需要注意的是 此方法只包括返回集合中的同级元素,而不包括子代 。 
using System.IO;
using System.Xml.Linq;namespace _10_1
{class Program{static void Main(string[] args){        ReturnNodesAfterSelf();#region ReturnNodesAfterSelf()void ReturnNodesAfterSelf(){XElement root = new("Categories",new XElement("Category",new XElement("CategoryID", Guid.NewGuid()),new XElement("CategoryName", "食品"),new XElement("Description", "可以吃的东西"))   //Category);      //Categoriesforeach (var item in root.Element("Category").Element("CategoryID").NodesAfterSelf()){Console.WriteLine((item as XElement).Value);}}#endregion ReturnNodesAfterSelf()}} 
}
//运行结果:
//食品
//可以吃的东西

更多推荐

C#的LINQ to XML 类中使用最多的三个类:XElement、XAttribute 和 XDocument

本文发布于:2023-11-16 11:46:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620917.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最多   类中   XML   LINQ   XAttribute

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!