C#学习笔记(十五) LINQ to XML

LINQ to XML

  1. XML:可扩展标记语言,用于存储和交换数据的重要方法,使用LINQ to XML可以简化XML的创建、查询和操作。
  2. 标记语言:它是文档的一组标签,提供了有关文档的信息并组织其内容。标记标签不是文档的数据,它是包含关于数据的数据,即是元数据。它旨在传递有关文档内容的特定类型的元数据。
  3. XML基础:XML文档中的数据包含一个XML树,它主要由嵌套元素组成;元素是XML树的基本要素,每一个元素由名字和数据组成;一些元素好包含其他嵌套的元素;元素由开始标签和关闭标签进行划分,开始标签由左尖括号开始,后面是元素名,紧接着是可选的特性,最后是右尖括号,如<PhoneNumber>;关闭标签从左尖括号开始,后面是斜杠,然后是元素名和右尖括号,如</PhoneNumber>;没有内容的元素可以只有一对尖括号,保留元素名和斜杠,如<PhoneNumber />;整个描述起来有:<PhoneNumber> Your Number </PhoneNumber>;
  4. XML文档必须有一个根元素包含其他所有元素;XML标签必须合理嵌套,并且区分大小写;XML特性是名字/值的配对,它包含了元素的额外元数据。特性部分的值必须包含在引号内,单/双引号皆可。
  5. 示例:
<Employees>
	<Employee>
			<Name>Persistant</Name>
			<PhoneNumber> 400-555-1996</PhoneNumber>
			<CellPhoe />
	</Employee>
	<Employee>
			<Name>Hardwork for yourself</Name>
			<PhoneNumber> 400-666-1998</PhoneNumber>
			<PhoneNumber> 400-999-2000</PhoneNumber>
	</Employee>
</Employees>	
  1. XML类:LINQ to XML有两种方式与XML配合使用,一种是LINQ to XML API,第二种是LINQ查询工具。LINQ to XML API 有许多表示XML树组件的类组成 最重要的XML类有XElement、XAttribute、XDocument。
  2. 可以作为XDocument节点的直接子节点有:XDeclaration节点、XDocumentType节点以及XElement节点,任意数量的XProcessingInstruction节点;如果在XDocument中有最高级别的XElement节点,则它就是XML树的根节点;根元素可以包含任意数量的嵌套XElement、XComment或XProcessingInstruction节点,在任何级别上嵌套;除了XAttribute类外,大部分XML树由XNode类继承。
  3. 创建、保存、加载和显示XML文档:示例如下
using System;
using System.Linq;
using System.Xml.Linq;

namespace test45
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument employees1 =       
                new XDocument(                              //创建XML文档
                    new XElement("Employees",               //创建根元素
                        new XElement("Name","Bob Smith"),   //创建元素
                        new XElement("Name","Sally Jones")  //创建元素
                )
            );
            employees1.Save(@"D:\Program Files (x86)\C# file\C# learn notes\test45\EmployeesFile.xml");     //保存文件
            XDocument employees2 = XDocument.Load(@"D:\Program Files (x86)\C# file\C# learn notes\test45\EmployeesFile.xml");  //加载XML文档
            Console.WriteLine(employees2);      //显示文档
        }
    }
}

执行结果:

在这里插入图片描述
9. 创建XML树:可以通过XDocument和XElement的构造函数在内存中创建一个XML文档,在这里,两个构造函数,第一个参数都是对象名,第二个参数以及之后的参数包含了XML树的节点。构造函数的第二个参数是一个params参数,即可以有任意多个参数。

using System;
using System.Linq;
using System.Xml.Linq;

namespace test46
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument Myself1 =                         //创建XML文档
                new XDocument( 
                    new XElement("Myclass",              //有且只能有一个根元素     
                        new XElement("automation",
                        new XElement("Name","khq"),
                        new XElement("class","1401班")
                        ),
                    new XElement("school",
                    new XElement("original","hpu"),
                    new XElement("now","csu")
                        )
                    )
                );
            Myself1.Save(@"D:\Program Files (x86)\C# file\C# learn notes\test46\Myclass.xml");
            XDocument Myself2 = XDocument.Load(@"D:\Program Files (x86)\C# file\C# learn notes\test46\Myclass.xml");
            Console.WriteLine(Myself2);
        }
    }
}

执行结果:

在这里插入图片描述
10. 使用XML树的值: 通过查询XML的方法来遍历XML树获取或修改值。其中的方法有以下几种。
Nodes:返回类型IEnumerbale,返回当前节点的所有子节点;
Elements:返回类型IEnumerbale,返回当前节点的Element子节点或具有某个名称的子节点;
Element:返回类型Xdocument或XElement,返回当前节点的第一个XElement子节点,或具有某个名称XElement的子节点;
Descendants:返回类型IEnumerable,返回所有XElement子代节点,或具有某个名称的子节点,不管出于当前节点下嵌套的什么层次;
DescendantsAndSelf:返回类型IEnumerable,和Descendants一样,但包括当前节点;
Ancestors:返回类型IEnumerable,返回所有上级XElement节点,或具有某个名称的上级XElement节点;
AncestorsAndSelf:和 Ancestor一样,但包括当前节点;
Parent:返回类型XElement,返回当前节点的父节点。

说明:对于Nodes,可以用类型作为OfType(type)参数,指定返回类型,比如IEnumerbale<XComment> comments = xd.Nodes().OfType<XComment>();对于Elements方法,可以使用无参数的Elements方法返回所有子XElement;使用单个name参数的Elements方法返回只具有该名称子XElements。比如IEnumerbale<XElement> empphones = emp.Elements("phonenumber"); Descendants和Ancestor不返回直接的子元素或子节点,而是忽略嵌套级别,包括所有之上或之下的节点。

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

namespace test47
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument employeeDoc = new XDocument(
               new XElement("Employees",
                    new XElement("employee1",
                        new XElement("name","khq"),
                        new XElement("phonenumber","199-555-1000")
                    ),
                    new XElement("employee2",
                         new XElement("name","ZWL"),
                         new XElement("phonenumber","188-666-1000"),
                         new XElement("phonenumber","188-666-1001")
                    )
               )
            );
            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("  {0}",phone.Value);
                }
            }
        }
    }
}

执行结果:

在这里插入图片描述
11. 增加节点以及操作XML:使用Add()方法增加任意类型的节点。

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

namespace test48
{
    class Program
    {
        static void Main(string[] args)
        {
            //使用Add()方法增加任意类型的节点
            XDocument xd = new XDocument(
                new XElement("root",
                    new XElement("First")
                )
            );
            Console.WriteLine(xd);
            XElement rt = xd.Element("root");
            rt.Add(new XElement("Second"));
            rt.Add(
                new XElement("Third"),
                new XComment("Important Message"),
                new XElement("Four")
            );
            Console.WriteLine("Modified Node");
            Console.WriteLine(xd);
        }
    }
}

执行结果:

在这里插入图片描述

  1. 使用XML特性:特性提供了XElement节点的额外信息,你为哪一个节点增加特性,特性就位于哪一个节点的开始标签中,然后通过这个节点利用Attribute()方法获取特性。如果以函数方法构造XML树,只需要在XElement节点的构造函数中包含XAttribute构造函数来增加特性。XAttribute构造函数有两种形式,一种接受name和Value,另一种接受现有XAttribute的引用。
//使用XML特性,他有name和Value两种属性
using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

namespace test49
{
    class Program
    {
        static void Main(string[] args)
        {   
            //name里面不能有空格,否则会报错
            XDocument xd = new XDocument(
                new XElement("root",
                    new XElement("my_info",
                         new XElement("name","khq"),
                         new XElement("class","automation_1802"),
                         new XAttribute("person_information",24)
                    )
                )
            );
            Console.WriteLine(xd);      //显示XML树
            XElement rt = xd.Element("root");
            XElement myif = rt.Element("my_info");
            XAttribute attr = myif.Attribute("person_information");     //通过特性所在的节点获取特性
            Console.WriteLine("person_age:{0}",attr.Value);
        }
    }
}

执行结果:

在这里插入图片描述

  1. 节点中的其他类型:包括XComment、XDeclaration、XProcessingInstruction。
    (1) XComment:XML注释由"<! – text – > ",new XComment("this is a comment");

    (2) XDeclaration:XML声明包括使用版本号、字符编码类型以及文档是否依赖外部引用,例如语句new XDeclaration("1.0","utf-8","yes");会产生<?xml version="1.0" encoding="utf-8" standalone ="yes"?>

    (3) XProcessingInstruction:XML处理指令提供XML文档如何被使用和翻译的额外数据,可以把处理指令用于关联XML文档和一个样式表。可以使用XProcessingInstruction构造函数包含处理指令,它接受两个字符串参数,目标和数据串。如果处理指令接受多个数据参数,这些参数必须位于第二个字符串参数中,例如new XProcessingInstruction("xml-stylesheet",@"href="stories",type = ""text/css""");
    这将产生XML文档<?xml-stylesheet href="stories.css" type="text/css"?>

  2. 使用LINQ to XML的LINQ查询:将LINQ to XML API和LINQ查询表达式结合起来使用,可以通过SetAttributeValue()方法设置或者修改特性的值。

//LINQ to XML API和LINQ查询表达式结合
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace test50
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument xd = new XDocument(
                new XElement("MyElement",
                    new XElement("first",
                        new XAttribute("color","red"),
                        new XAttribute("size","samll")
                    ),
                    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);
            xd.Save(@"D:\Program Files (x86)\C# file\C# learn notes\test50\SimpleSample.xml");
            XDocument xdoc = XDocument.Load(@"D:\Program Files (x86)\C# file\C# learn notes\test50\SimpleSample.xml");
            XElement rt = xdoc.Element("MyElement");
           
            var xyz = from e in rt.Elements()
                      where e.Name.ToString().Length == 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.WriteLine();
            var xdocl = from m in rt.Elements()
                        select new {m.Name,color = m.Attribute("color")};
            foreach(var x in xdocl)
            {
                Console.WriteLine(x);
            }
            foreach(var x in xdocl)
            {
                Console.WriteLine("Name:{0,-6},   color:{1,-7}",x.Name,x.color.Value);
            }
        }
    }
}

执行结果:

在这里插入图片描述在这里插入图片描述在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值