XAttribute类

来源:互联网 发布:函数式编程语言推荐 编辑:程序博客网 时间:2024/05/10 13:24

XAttribute类是用来处理XML中元素的属性的,属性是与元素相关联的名称/值对,在操作上和元素有很多相似之处.属性不能作为XML树中的节点,因此不是派生于XNode类.每个属性必须有一个限定名,该名称对元素来说是唯一的.下面就用几个小示例体验一下XAttribute类吧.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ConsoleApplication1
{
   
class Program
    {
       
static void Main(string[] args)
        {
           
//创建一个测试树
            XElement tree = new XElement("Root",
           
new XElement("Person"));
            PrintTree(
"创建一个测试树", tree);

           
//为Person元素添加一个Id属性
            tree = new XElement("Root",
           
new XElement("Person",
               
new XAttribute("Id", 1)));
            PrintTree(
"为Person元素添加一个Id属性", tree);

           
//设置Person元素的Id属性为2
            tree.Element("Person").SetAttributeValue("Id", 2);
            PrintTree(
"设置Person元素的Id属性为2", tree);

           
//移除Person元素的Id属性
            tree.Element("Person").Attribute("Id").Remove();
            PrintTree(
"移除Person元素的Id属性", tree);
        }

       
private static void PrintTree(string info, XElement tree)
        {
            Console.WriteLine(info);
            Console.WriteLine(tree);
            Console.WriteLine(
"----------------------------------");
        }
    }
}

原创粉丝点击