LINQ系列:LINQ to XML类

  LINQ to XML由System.Xml.Linq namespace实现,该namespace包含处理XML时用到的所有类。在使用LINQ to XML时需要添加System.Xml.Linq.dll的引用,在代码声明中添加using:

using System.Xml.Linq;

1. System.Xml.Linq namespace的类及其描述

描述
XAttribute XML中的一个属性
XCData CDATA文本节点
XComment XML注释
XContainer 一个抽象基类,表示具有子节点的节点
XDeclaration XML声明
XDocument XML文档,该类派生自XContainer类
XDocumentType XML DTD(文档类型定义)
XElement XML元素,是XContainer的派生类
XName XML元素或属性的名称
XNamespace XML命名空间
XNode XML元素树的节点
XNodeDocumentOrderComparer 根据节点在XML文档内的顺序对它们进行比较
XNodeEqualityComparer 根据节点的值对它们进行比较
XObject 表示XNodes和XAttributes的抽象类
XObjectChange XObject事件发生时的事件类型
XObjectChangeEventArgs 为Changing和Chenged事件提供信息和数据
XObjectChangeEventHandler 处理XObject中Changed和Changing事件的方法
XProcessingInstruction XML处理指令
XText XML文本

  示例:XML声明指定XML版本、XML文档的编码,以及XML文档是否是一个独立的文件。

// using System.Xml.Linq;
XDocument doc = new XDocument
(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("Root", "LINQ to XML")
);
string xml = doc.Declaration.ToString() + Environment.NewLine + doc.ToString();
Console.WriteLine(xml);

  运行结果:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>LINQ to XML</Root>

2. XElement类

  XElement类表示XML元素,它是XContainer类的派生类,而XContainer类又派生于XNode类。一个元素就是一个节点,XElement是LINQ to XML最重要最基本的类之一,它包含所有创建和操作XML元素所必需的功能。通过它可以创建元素,添加和修改元素的属性,操作元素的内容等。

XDocument doc = new XDocument
(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XComment("Created by LINQ to XML"),
    new XElement
    (
        "Products",
        new XElement("ProductID", 1),
        new XElement("ProductName", "LINQ to XML"),
        new XElement("UnitPrice", 10m)
    )
);
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<!--Created by LINQ to XML-->
<Products>
  <ProductID>1</ProductID>
  <ProductName>LINQ to XML</ProductName>
  <UnitPrice>10</UnitPrice>
</Products>

3. XAttribute类

  XAttribute类用来处理属性,属性是与元素相关联的名称/值对。

XElement product = new XElement
(
    "Root",
    new XElement
    (
        "Product",
        new XAttribute("id", 1)
    )
);
<Root>
  <Product id="1" />
</Root>
XElement product = new XElement
(
    "Root",
    new XElement
    (
        "Product",
        new XAttribute("ProductID", 1),
        new XAttribute("ProductName", "LINQ to XML")
    )
);
<Root>
  <Product ProductID="1" ProductName="LINQ to XML" />
</Root>

  删除元素属性:

XAttribute attr = product.Element("Product").Attribute("ProductName");
attr.Remove();

4. XDocument类

  XDocument类提供了处理有效XML文档的方法,包括声明、注释和处理指令。XDocument类派生自XContainer类,可以有子节点。XML标准限值XDocument对象只包含单个XElement子节点,此节点作为根节点或跟元素。

posted @ 2014-11-01 10:56  libingql  阅读(1341)  评论(0编辑  收藏  举报