简书面面观

C#沉淀-Linq to XML实战

2018-09-25  本文已影响23人  东南有大树

XML类

Linq to XML可以以两种方式和XML配合。第一种方式是作为简化的XML操作API,和二种方式是使用本章前面看到的Linq查询工具

Linq to XML API由很多表示XML树组件的类组成,其中有三个类比较重要:XElement/XAttribute/XDocument

从示例出发:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Xml.Linq;

namespace CodeForLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            //XDocument表示一个XML文档
            //XElement表示一个XML元素
            XDocument employees1 =
                new XDocument(
                    //创建一个Employees根节点
                    new XElement("Employees",
                        //创建两个子节点
                        new XElement("Name", "Bob Smith"),
                        new XElement("Name", "Sally Jones") 
                        )
                    );

            //通过Save方法将XML文档保存
            employees1.Save("Employees.xml");

            //通过Load方法加载XML文档
            XDocument employees2 = XDocument.Load("Employees.xml");

            //打印出XML文档结构
            Console.WriteLine(employees2.ToString());

            Console.ReadKey();
        }
    }
}

输出:

<Employees>
  <Name>Bob Smith</Name>
  <Name>Sally Jones</Name>
</Employees>

XML树的嵌套关系

?表示0个或1个;*表示这个或多个

语法解析:

public XDocument(params object[] content);

参数表示文档所包含的内容,即要添加到此文档的内容对象的参数列表,上例添加了一个根节点

public XElement(XName name, params object[] content);

第一个参数是对象名

第二个参数以及之后的参数包含了XML树的节点;第二个参数是一个Params参数,也就是说可以有任意多个参数

然后在根点中又添加了两个节点

使用XML树的值

用于获取XML树的值的方法有:

示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Xml.Linq;

namespace CodeForLinq
{
    class Program
    {
        static void Main(string[] args)
        {

            //XDocument表示一个XML文档
            //XElement表示一个XML元素
            XDocument employees1 =
                new XDocument(

                //创建一个Employees根节点
                    new XElement("Employees",

                //创建两个子节点
                        new XElement("Employee",
                            new XElement("Name", "Bob Smith"),
                            new XElement("PhoneNumber", "13161861814")),
                        new XElement("Employee",
                            new XElement("Name", "Sally Jones"),
                            new XElement("PhoneNumber", "13161861815"),
                            new XElement("PhoneNumber", "13161861816"))

                            ));

            //获取第一个名为"Employees"的子XElement
            XElement root = employees1.Element("Employees");//其实就是根节点
            IEnumerable<XElement> employess = root.Elements();//根节点下所有的子节点

            foreach (XElement emp in employess)
            {
                //获取第一个名为"Name"的子XElement
                XElement empNameNode = emp.Element("Name");
                Console.WriteLine(empNameNode.Value);

                //获取第一个名为"PhoneNumber"的子XElement
                IEnumerable<XElement> empPhones = emp.Elements("PhoneNumber");
                foreach (XElement phone in empPhones)
                    Console.WriteLine(phone.Value);
            }

            Console.ReadKey();
        }
    }
}

增加节点以及操作XML

可以使用Add方法为现在元素增加子元素

Add方法允许一次增加任意多个元素,不管增加的节点类型是什么类型

示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Xml.Linq;

namespace CodeForLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建xml文档,并添加一个根节点一个子节点
            XDocument xd = new XDocument(
                new XElement("root",
                    new XElement("first")
                    )
                );

            Console.WriteLine("Origianl tree");
            Console.WriteLine(xd);//展示一下目前的树结构
            Console.WriteLine();

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

            //添加子元素
            rt.Add(new XElement("second"));

            //连续添加三个元素
            rt.Add(
                new XElement("thrid"),
                new XElement("fourth"),
                new XElement("fifth")
                );
            //Add方法会把新添加的子节点放到已有的子节点之后

            Console.WriteLine("Modified tree");
            Console.WriteLine(xd);

            Console.ReadKey();
        }
    }
}

其他常用方法

使用XML特性(属性)

示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Xml.Linq;

namespace CodeForLinq
{
    class Program
    {
        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);

            Console.ReadKey();
        }
    }
}

输出:

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

XAttributeXElement的构造中设置其属性值,第一个参数指定属性名,第二个参数指定属性值

再来看看获取特性值的示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Xml.Linq;

namespace CodeForLinq
{
    class Program
    {
        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);
            Console.WriteLine("---------");

            XElement rt = xd.Element("root");

            XAttribute color = rt.Attribute("color");
            XAttribute size = rt.Attribute("size");

            Console.WriteLine("颜色值:{0}",color.Value);
            Console.WriteLine("大小值:{0}", size.Value);

            Console.ReadKey();
        }
    }
}

输出:

<root color="red" size="large">
  <first />
  <second />
</root>
---------
颜色值:red
大小值:large

移除特性

示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Xml.Linq;

namespace CodeForLinq
{
    class Program
    {
        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);
            Console.WriteLine("---------");

            XElement rt = xd.Element("root");

            //第一种移除方法
            rt.Attribute("color").Remove();
            //第二种移除方法
            rt.SetAttributeValue("size", null);

            Console.WriteLine(xd);

            Console.ReadKey();
        }
    }
}

输出

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

增加与修改特性值

示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Xml.Linq;

namespace CodeForLinq
{
    class Program
    {
        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);
            Console.WriteLine("---------");

            XElement rt = xd.Element("root");

            //修改特性值
            rt.SetAttributeValue("color","green");
            //添加一个新的特性
            rt.SetAttributeValue("width", "narrow");

            Console.WriteLine(xd);

            Console.ReadKey();
        }
    }
}

输出:

<root color="red" size="large">
  <first />
  <second />
</root>
---------
<root color="green" size="large" width="narrow">
  <first />
  <second />
</root>

关于节点的其他类型

完整示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Xml.Linq;

namespace CodeForLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument xd = new XDocument(
                new XDeclaration("1.0","utf08","yes"),
                new XComment("这是一行注释"),
                new XProcessingInstruction ("xml-stylesheet",@"href=""stories"" type=""text/css"""),

                new XElement("root",
                    new XAttribute("color","red"),
                    new XAttribute("size","large"),
                    new XElement("first"),
                    new XElement("second")
                    )
                );

            Console.WriteLine(xd);

            Console.ReadKey();
        }
    }
}

输出:

<!--这是一行注释-->
<?xml-stylesheet href="stories" type="text/css"?>
<root color="red" size="large">
  <first />
  <second />
</root>

使用Linq to XML的Linq查询

示例一:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Xml.Linq;

namespace CodeForLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument xd = new XDocument(
                new XDeclaration("1.0", "utf08", "yes"),
                new XComment("这是一行注释"),
                new XProcessingInstruction("xml-stylesheet", @"href=""stories"" type=""text/css"""),

                new XElement("root",

                    new XAttribute("color", "red"),
                    new XAttribute("size", "large"),

                    new XElement("first",
                        new XAttribute("color", "red"),
                        new XAttribute("size", "large")
                    ),
                    new XElement("second",
                        new XAttribute("color", "green"),
                        new XAttribute("size", "large")
                    ),
                    new XElement("thrid",
                        new XAttribute("color", "yello"),
                        new XAttribute("size", "large")
                    )
                    )
                );

            xd.Save("Hello.xml");
            Console.WriteLine(xd);

            XDocument doc = XDocument.Load("Hello.xml");
            XElement root = doc.Element("root");

            var xyz = from e in root.Elements()
                      where e.Name.ToString().Length == 5 // 获取五个字符的元素
                      select e;

            foreach (var item in xyz)
            {
                Console.WriteLine(item.Name.ToString());
            }

            Console.WriteLine("-------");

            foreach (var item in xyz)
            {
                Console.WriteLine("Name:{0}, Color:{1}, Size:{2}",item.Name,item.Attribute("color").Value,item.Attribute("size").Value);
            }
            Console.ReadKey();
        }
    }
}

输出:

<!--这是一行注释-->
<?xml-stylesheet href="stories" type="text/css"?>
<root color="red" size="large">
  <first color="red" size="large" />
  <second color="green" size="large" />
  <thrid color="yello" size="large" />
</root>
first
thrid
-------
Name:first, Color:red, Size:large
Name:thrid, Color:yello, Size:large

示例二:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Xml.Linq;

namespace CodeForLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument xd = new XDocument(
                new XDeclaration("1.0", "utf08", "yes"),
                new XComment("这是一行注释"),
                new XProcessingInstruction("xml-stylesheet", @"href=""stories"" type=""text/css"""),

                new XElement("root",

                    new XAttribute("color", "red"),
                    new XAttribute("size", "large"),

                    new XElement("first",
                        new XAttribute("color", "red"),
                        new XAttribute("size", "large")
                    ),
                    new XElement("second",
                        new XAttribute("color", "green"),
                        new XAttribute("size", "large")
                    ),
                    new XElement("thrid",
                        new XAttribute("color", "yello"),
                        new XAttribute("size", "large")
                    )
                    )
                );

            xd.Save("Hello.xml");
            Console.WriteLine(xd);

            Console.WriteLine("\n-------");

            XDocument doc = XDocument.Load("Hello.xml");
            XElement root = doc.Element("root");

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

            foreach (var item in xyz)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("\n-------");

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

输出:

<!--这是一行注释-->
<?xml-stylesheet href="stories" type="text/css"?>
<root color="red" size="large">
  <first color="red" size="large" />
  <second color="green" size="large" />
  <thrid color="yello" size="large" />
</root>

-------
{ Name = first, color = red }
{ Name = second, color = green }
{ Name = thrid, color = yello }

-------
first , color:red
second, color:green
thrid , color:yello
上一篇 下一篇

猜你喜欢

热点阅读