(十一)CSharp-LINQ-LINQToXML(4)

一、XML 类

1、创建、保存、加载和显示 XML 文档

        static void Main(string[] args)
        {
            XDocument employees1 =
                new XDocument(//创建 XML 文档
                    new XElement("Employees",//创建根元素
                    new XElement("Name", "Box Smith"),//创建元素
                    new XElement("Name", "Sally Jones")//创建元素
                    )
                    );

            employees1.Save("EmployeesFile.xml");//保存到文件

            //将保存的文档加载到新变量中
            XDocument employees2 = XDocument.Load("EmployeesFile.xml");

            Console.WriteLine(employees2);//显示文档
            Console.ReadKey();
        }

输出结果:

><Employees>
  <Name>Box Smith</Name>
  <Name>Sally Jones</Name>
</Employees>
1)创建 XML 树
        static void Main(string[] args)
        {
            XDocument employeeDoc =
                new XDocument(//创建文档
                    new XElement("Employees",//创建根元素

                    new XElement("Employee",//第一个 Employee 元素
                    new XElement("Name", "Box Smith"),
                    new XElement("PhoneNumber", "408-555-10000")),

                    new XElement("Employee",//第二个 Employee 元素
                    new XElement("Name", "Sally Jones"),
                    new XElement("PhoneNumber", "415-555-2000"),
                     new XElement("PhoneNumber", "415-555-2001"))

                    )
                    );

            Console.WriteLine(employeeDoc);//显示文档
            Console.ReadKey();
        }

输出结果:

<Employees>
  <Employee>
    <Name>Box Smith</Name>
    <PhoneNumber>408-555-10000</PhoneNumber>
  </Employee>
  <Employee>
    <Name>Sally Jones</Name>
    <PhoneNumber>415-555-2000</PhoneNumber>
    <PhoneNumber>415-555-2001</PhoneNumber>
  </Employee>
</Employees>
2)使用 XML 树的值

表20-2 查询 XML 的方法

方法名称返回类型描述
NodesXdocument,XElementIEnumerable<object>返回当前节点的所有节点(不管是什么类型)
ElementsXdocument,XElementIEnumerable<XElement>返回当前节点的 XElement 子节点,或所有具有某个名字的子节点
ElementXdocument,XElementXElement返回当前节点的第一个 XElement 子节点,或具有某个名字的子节点
DescendantsXElementIEnumerable<XElement>返回所有的 XElement 子代节点,或所有具有某个名字的 XElement 子代节点,不管它们处于当前节点下什么嵌套级别
DescendantsAndSelfXElementIEnumerable<XElement>和 Descendants 一样,但是包括当前节点
AncestorsXElementIEnumerable<XElement>返回所有上级 XElement 节点,或者所有具有某个名字的上级 XElement 节点
AncestorsAndSelfXElementIEnumerable<XElement>和 Ancestors 一样,但是包括当前节点
ParentXElementXElement返回当前节点的父节点
  • Nodes
//获取 XComment 节点
IEnumerable<XComment> comments = xd.Nodes().OfType<XComment>();
  • Elements
//获取名为 PhoneNumer 的子 XElement 节点
IEnumerable<XElement> empPhones = emp.Element("PhoneNumer");
  • Element
    获取第一个子 XElement 节点。

Element 和 Elements 方法示例:

       static void Main(string[] args)
        {
            XDocument employeeDoc =
                new XDocument(
                    new XElement("Employees",

                    new XElement("Employee",
                    new XElement("Name", "Box Smith"),
                    new XElement("PhoneNumber", "408-555-10000")),

                    new XElement("Employee",
                    new XElement("Name", "Sally Jones"),
                    new XElement("PhoneNumber", "415-555-2000"),
                     new XElement("PhoneNumber", "415-555-2001"))

                    )
                    );

            XElement root = employeeDoc.Element("Employees");
            IEnumerable<XElement> employees = root.Elements();

            foreach(XElement emp in employees)
            {
                XElement empNameNode = emp.Element("Name");
                Console.WriteLine(empNameNode.Value);

                IEnumerable<XElement> empPhones = emp.Elements("PhoneNumber");
                foreach (XElement phone in empPhones)
                    Console.WriteLine($"     { phone.Value }");
            }

            Console.ReadKey();
        }

输出结果:

Box Smith
408-555-10000
Sally Jones
415-555-2000
415-555-2001

3)增加节点以及操作 XML
   static void Main(string[] args)
        {
            XDocument xd = new XDocument(//创建 XML 树
                new XElement("root",
                new XElement("first")
                )
                );

            Console.WriteLine("Original tree");
            Console.WriteLine(xd);Console.WriteLine();//显示树

            XElement rt = xd.Element("root");//获取第一个元素
            rt.Add(new XElement("second"));//添加子元素
            rt.Add(new XElement("third"),//再添加3个子元素
                new XComment("Important Comment"),
                new XElement("fourth"));

            Console.WriteLine("Modified tree");
            Console.WriteLine(xd);//显示 Modified tree

            Console.ReadKey();
        }

输出结果:

Original tree
<root>
  <first />
</root>

Modified tree
<root>
  <first />
  <second />
  <third />
  <!--Important Comment-->
  <fourth />
</root>

表20-3 操作 XML 的方法

方法名称从哪里调用描述
Add父节点在当前节点的既有子节点前后加新的子节点
AddFirst父节点在当前节点的既有子节点前增加新的子节点
AddBeforeSelf节点在同级别的当前节点之前增加新的节点
AddAfterSelf节点在同级别的当前节点之后增加新的节点
Remove节点删除当前所选的节点及其内容
RemoveNodes节点删除当前所选的 XElement 及其内容
SetElement父节点设置节点的内容

2、使用 XML 特性

特性提供了有关 XElement 节点的额外信息,它放在 XML 元素的开始标签中。
如:

        static void Main(string[] args)
        {
            XDocument xd = new XDocument(
                new XElement("root",
                new XAttribute("color", "red"),//特性构造函数
                new XAttribute("Size", "large"),//特性构造函数
                new XElement("first"),
                new XElement("second")
                )
                );

            Console.WriteLine(xd);

            XElement rt = xd.Element("root");//获取元素

            XAttribute color = rt.Attribute("color");
            XAttribute size = rt.Attribute("Size");//获取特性

            Console.WriteLine($"color is {color.Value}");//显示特性值
            Console.WriteLine($"size is {size.Value}");

//移除特性
//rt.Attribute("color").Remove();//移除 color 特性
//rt.SetAttributeValue("Size",nulll);//移除 size 特性

//变更特性值
//rt.SetAttributeValue("Size","medium");
//rt.SetAttributeValue("width","narrow");//如果没有这个特性,就添加特性
            Console.ReadKey();
        }

输出结果:

<root color="red" Size="large">
  <first />
  <second />
</root>
color is red
size is large

2、其他类型的节点

1)XComment
new XComment("This is a comment");

XML 文档行为:

<!--This is a comment-->
2)XDeclaration

XML 文档从包含 XML 使用的版本号、使用的字符编码类型以及文档是否依赖外部引用的一行开始。

new XDeclaration("1.0", "utf-8", "yes");

XML 文档行:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
3)XProcessingInstruction

XML 处理指令用于提供关于 XML 文档的使用和解释方法的额外数据。处理指令最常用于关联 XML 文档和样式表。

可以使用 XProcessingInstruction 构造函数来包含处理指令。它接受两个字符串参数:目标和数据串。如果处理指令接受多个数据参数,这些参数必须包含在 XProcessingInstruction 构造函数的第二个字符串参数中。

new XProcessingInstruction("XML-stypesheet",
						    @"href=""stories"", type=""text/css""")

XML 文档行:

<?xml-stylesheet href="stories.css" type=""text/css?>

例如:

     static void Main(string[] args)
        {
            XDocument xd = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XComment("This is a comment"),
                new XProcessingInstruction("xml-stylesheet",
                                            @"href=""stories.css"" type=""text/css"""),
                new XElement("root",
                new XElement("first"),
                new XElement("second")
                )
                );

            Console.WriteLine(xd);

            Console.ReadKey();
        }

输出结果:

<!--This is a comment-->
<?xml-stylesheet href="stories.css" type="text/css"?>
<root>
  <first />
  <second />
</root>

二、使用 LINQ to XML 的 LINQ 查询

1)创建保存 XML 文档:

示例:

        static void Main(string[] args)
        {
            XDocument xd = new XDocument(
                new XElement("MyElements",
                new XElement("first",
                new XAttribute("color","red"),
                new XAttribute("size","small")),

                 new XElement("second",
                new XAttribute("color", "red"),
                new XAttribute("size", "medium")),

                 new XElement("third",
                new XAttribute("color", "blue"),
                new XAttribute("size", "large"))));


            Console.WriteLine(xd);//显示 XML 树
            xd.Save("SimpleSample.xml");//保存 XML 树
            Console.ReadKey();
        }

XML 文档行:

<MyElements>
  <first color="red" size="small" />
  <second color="red" size="medium" />
  <third color="blue" size="large" />
</MyElements>

2)加载 XML 文档,使用 LINQ 查询 XML:

        static void Main(string[] args)
        {
            XDocument xd =  XDocument.Load("SimpleSample.xml"); //加载文档
            XElement rt = xd.Element("MyElements"); //获取根元素

            var xyz = from e in rt.Elements() //选择名称包含
                      where e.Name.ToString().Length == 5 //5个字符的元素
                      select e;

            foreach (XElement x in xyz)
                Console.WriteLine(x.Name.ToString());//显示所选的元素

            Console.WriteLine();

            foreach (XElement x in xyz)
                Console.WriteLine("Name:{0}, color: {1},size: {2}",
                                  x.Name,
                                  x.Attribute("color").Value,
                                  x.Attribute("size").Value);

            Console.ReadKey();
        }

输出结果:

first
third

Name:first, color: red,size: small
Name:third, color: blue,size: large

3)如下代码使用了一个简单的查询来获取 XML 树的所有顶层元素,并且为每一个元素创建了一个匿名类型的对象。

        static void Main(string[] args)
        {
            XDocument xd =  XDocument.Load("SimpleSample.xml"); //加载文档
            XElement rt = xd.Element("MyElements"); //获取根元素

            var xyz = from e in rt.Elements()
                      select new { e.Name, color = e.Attribute("color") };

            foreach (var x in xyz)
                Console.WriteLine(x);//默认格式化

            Console.WriteLine();

            foreach (var x in xyz)
                Console.WriteLine("{0,-6},    color: {1,-7}",x.Name,x.color.Value);

            Console.WriteLine();

            Console.ReadKey();
        }

//创建匿名类型:new { e.Name, color = e.Attribute("color") };

输出结果:

{ Name = first, color = color="red" }
{ Name = second, color = color="red" }
{ Name = third, color = color="blue" }

first ,    color: red
second,    color: red
third ,    color: blue

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值