加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

LINQ to XML 学习总结

发布时间:2020-12-15 23:36:35 所属栏目:百科 来源:网络整理
导读:一、命名空间 System.Xml.Linq.dll程序集定义了三个命名空间:System.Xml.Linq,System.Xml.Schema 和 System.Xml.XPath 最核心的是System.Xml.Linq, 定义了对应 XML 文档个方面的很多类型 System.Xml.Linq成员 Meaning in Life XAttribute 表示在一个给定的

一、命名空间

System.Xml.Linq.dll程序集定义了三个命名空间:System.Xml.Linq,System.Xml.Schema 和 System.Xml.XPath

  最核心的是System.Xml.Linq, 定义了对应 XML 文档个方面的很多类型

System.Xml.Linq成员

Meaning in Life

XAttribute

表示在一个给定的XML元素的XML属性

XComment

代表了一个XML注释

XDeclaration

表示XML文档的开放的规范

XDocument

表示XML文档的整体

XElement

代表一个给定的XML文档中的元素

XName/XNamespace

一个非常简单的方式来定义和XML命名空间提供参考

二、编程方式创建XML文档

以前的 .NET XML编程模型需要使用很多冗长的 DOM API,而 LINQ to XML 则完全可以用与 DOM 无关的方式与 XML 文档交互。这样不但大大减少了代码行,而且这种编程模型可以直接映射到格式良好的XML文档结构。

using System.Xml.Linq;
static void Main(string[] args)
        {
            //创建一个Xml元素
            XElement inventory =
              new XElement("Inventory",new XElement("Car",new XAttribute("ID","1"),//在此节点添加一个ID属性
              new XElement("Color","Green"),new XElement("Make","BMW"),new XElement("PetName","Stan")
              )
            );

            // 输出Xml文件
            Console.WriteLine(inventory); 

            Console.ReadKey();
        }

内存中创建XML文档
	static void CreateFunctionalXmlDoc()
        {
            XDocument inventoryDoc =
            new XDocument(
                new XDeclaration("1.0","utf-8","yes"),new XComment("Current Inventory of AutoLot"),new XElement("Inventory",new XElement("Color","Stan")
                    ),"2"),"Pink"),"Yugo"),"Melvin")
                    )
                )
            );
            // 显示文档保存到磁盘. 
            Console.WriteLine(inventoryDoc);
            inventoryDoc.Save("SimpleInventory.xml");
        }

三、使用Linq查询创建XML文档
 	static void CreateXmlDocFromArray()
        {
            //一个匿名数组创建匿名类型。 
            var data = new[] { 
            new { PetName = "Melvin",ID = 10 },            new { PetName = "Pat",ID = 11 },            new { PetName = "Danny",ID = 12 },            new { PetName = "Clunker",ID = 13 } 
          };

            // Now enumerate over the array to build 
            // an XElement. 
            XElement vehicles =
                new XElement("Inventory",from c in data select new XElement("Car",c.ID),c.PetName)
                    )
                );
            Console.WriteLine(vehicles);
        }


四、加载XML内容

下面的示例演示了如何从文件中加载xml:

	public static void LoadFromFile()
        {
     	     XElement root = XElement.Load("SimpleInventory.xml");
             Console.WriteLine(root.ToString());
        }

也可以使用Parse方法从一个字符串加载xml:

	public static void LoadFromString()
        {
            XElement root = XElement.Parse(@"
                <Categories>
                  <Category>
                    <CategoryID>1</CategoryID>
                    <CategoryName>Beverages</CategoryName>
                    <Description>Soft drinks,coffees,teas,beers,and ales</Description>
                  </Category>
                </Categories>
            ");

            Console.WriteLine(root.ToString());
        }


五、遍历内存中的XML文档


XML示例

<?xml version="1.0" encoding="utf-8"?>
<Inventory>
  <Car carID ="0">
    <Make>Ford</Make>
    <Color>Blue</Color>
    <PetName>Chuck</PetName>
  </Car>
  <Car carID ="1">
    <Make>VW</Make>
    <Color>Silver</Color>
    <PetName>Mary</PetName>
  </Car>
  <Car carID ="2">
    <Make>Yugo</Make>
    <Color>Pink</Color>
    <PetName>Gipper</PetName>
  </Car>
  <Car carID ="55">
    <Make>Ford</Make>
    <Color>Yellow</Color>
    <PetName>Max</PetName>
  </Car>
  <Car carID ="98">
    <Make>BMW</Make>
    <Color>Black</Color>
    <PetName>Zippy</PetName>
  </Car>
</Inventory>

加载
        static void Main(string[] args)
        {
            Console.WriteLine("***** 有趣的LINQ to XML *****n");

            // 将inventory.xml文档加载到内存中。
            XElement doc = XElement.Load("SimpleInventory.xml"); 
          //遍历
          PrintAllPetNames(doc); 
          Console.WriteLine(); 
            //查询
          GetAllFords(doc); 

          Console.ReadLine(); 
        }


        /// <summary>
        /// 遍历
        /// </summary>
        /// <param name="doc"></param>
        static void PrintAllPetNames(XElement doc)
        {
            var petNames = from pn in doc.Descendants("PetName")
                           select pn.Value;
            foreach (var name in petNames)
                Console.WriteLine("Name: {0}",name);
        }


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="doc"></param>
        static void GetAllFords(XElement doc)
        {
            var fords = from c in doc.Descendants("Make")
                        where c.Value == "Ford"
                        select c;
            foreach (var f in fords)
                Console.WriteLine("Name: {0}",f);
        }

六、在原xml文件中循环添加节点
/// <summary>
        /// 在原xml文件中循环添加节点
        /// </summary>
        /// <param name="doc"></param>
        static void AddNewElements(XElement doc)
        {
            // 添加5个新的 
            for (int i = 0; i < 5; i++)
            {
                //创建一个新的 XElement 
                XElement newCar =
                    new XElement("Car",i + 1000),"Ford"),"")
                    );
                // 添加到doc. 
                doc.Add(newCar);
            }
            // 显示新的doc
            Console.WriteLine(doc);
        }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读