LINQ to XML 学习总结

一、命名空间

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("Car", new XAttribute("ID", "1"),
                        new XElement("Color", "Green"),
                        new XElement("Make", "BMW"),
                        new XElement("PetName", "Stan")
                    ),
                    new XElement("Car", new XAttribute("ID", "2"),
                        new XElement("Color", "Pink"),
                        new XElement("Make", "Yugo"),
                        new XElement("PetName", "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",
                        new XAttribute("ID", c.ID),
                        new XElement("PetName", 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", new XAttribute("ID", i + 1000),
                        new XElement("Color", "Green"),
                        new XElement("Make", "Ford"),
                        new XElement("PetName", "")
                    );
                // 添加到doc. 
                doc.Add(newCar);
            }
            // 显示新的doc
            Console.WriteLine(doc);
        }







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值