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的类及其描述

描述
XAttributeXML中的一个属性
XCDataCDATA文本节点
XCommentXML注释
XContainer一个抽象基类,表示具有子节点的节点
XDeclarationXML声明
XDocumentXML文档,该类派生自XContainer类
XDocumentTypeXML DTD(文档类型定义)
XElementXML元素,是XContainer的派生类
XNameXML元素或属性的名称
XNamespaceXML命名空间
XNodeXML元素树的节点
XNodeDocumentOrderComparer根据节点在XML文档内的顺序对它们进行比较
XNodeEqualityComparer根据节点的值对它们进行比较
XObject表示XNodes和XAttributes的抽象类
XObjectChangeXObject事件发生时的事件类型
XObjectChangeEventArgs为Changing和Chenged事件提供信息和数据
XObjectChangeEventHandler处理XObject中Changed和Changing事件的方法
XProcessingInstructionXML处理指令
XTextXML文本

  示例: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子节点,此节点作为根节点或跟元素。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值