LINQ to Objects LINQ to XML

"术语“LINQ to Objects”是指直接对任意 IEnumerable 或 IEnumerable<T> 集合使用 LINQ 查询,无需使用中间 LINQ 提供程序或 API,如 LINQ to SQL 或 LINQ to XML 可以使用 LINQ 来查询任何可枚举的集合,如 List<T>Array 或 Dictionary<TKey, TValue> 该集合可以是用户定义的集合,也可以是 .NET Framework API 返回的集合。

从根本上说,LINQ to Objects 表示一种新的处理集合的方法。 采用旧方法,您必须编写指定如何从集合检索数据的复杂的 foreach 循环。 而采用 LINQ 方法,您只需编写描述要检索的内容的声明性代码。

另外,与传统的 foreach 循环相比,LINQ 查询具有三大优势:

  1. 它们更简明、更易读,尤其在筛选多个条件时。

  2. 它们使用最少的应用程序代码提供强大的筛选、排序和分组功能。

  3. 无需修改或只需做很小的修改即可将它们移植到其他数据源。

通常,您要对数据执行的操作越复杂,就越能体会到 LINQ 相较于传统迭代技术的优势。"

----------------------------------------------------------------------------------------------------------------------------------------------------------------MSDN

LINQ不仅能查询实现泛型IEnumerable<T>接口或泛型IQueryable<T>接口的类型,也能查询实现IEnumerable接口的类型。

IEnumerable  公开枚举器,该枚举器支持在非泛型集合上进行简单迭代。

IEnumerable<T> 公开枚举器,该枚举器支持在指定类型的集合上进行简单迭代。

IQueryable<T> 提供对数据类型已知的特定数据源的查询进行计算的功能。

LINQ to XML

LINQ to XML是可以使用LINQ在内存中操作XML的编程接口,将XML文档载入内存中去,可以使用LINQ表达式和查询运算符处理XML,之后可以序列化XML,保存到磁盘或发送到Internet.

LINQ to XML提供与以前的文档对象模型DOM类似的功能,却更加简便和医用,结合LINQ表达式和查询运算符,可以方便的查询XML。

LINQ to XML 使用XDocument类表示XML文档。

创建XML文档

XDocument.Parse
XDocument.Load
static void Main(string[] args)
        {
            //从URI加载 XML 文档生成 XDocument 对象
            XDocument doc = XDocument.Load("http://rss.sina.com.cn/news/marquee/ddt.xml");

            //为了方便查看,省略一些子节点
            //doc.Descendants("item").Remove();

            //为了方便查看,省略注释的一些内容
            foreach (var n in doc.Nodes())
            {
                XComment comm = n as XComment;
                if (comm != null)
                    comm.Value = string.Format("{0} ...... ",comm.Value.Substring(0, 30));
            }
            
            Console.WriteLine(doc);
            Console.ReadKey();
        }

 LINQ to XML使用XElement类表示XML元素。

XElement
using System;
using System.Xml.Linq;
using System.IO;

namespace DemoXElement1
{
    class Program
    {
        static void Main(string[] args)
        {
            /*XDocument xdoc = new XDocument(new XElement("林晚荣的老婆"));
            xdoc.Root.Add(new XElement("云出公主", "肖青璇"), new XElement("霓裳公主", "秦仙儿"), new XElement("金陵才女", "洛凝"));

            Console.WriteLine(xdoc);
            Console.ReadKey();*/
            XElement root = new XElement("林晚荣", new XComment("林晚荣家庭简介"), new XAttribute("年龄", "25"), new XAttribute("职位", "大华元帅"));
            XElement child = new XElement("老婆");
            child.Add(new XAttribute("人数", "14"));

            XDocument doc = new XDocument(new XComment ("林晚荣个人简介"),root);
            doc.Declaration = new XDeclaration("1.0", "utf-16", "yes");
            doc.Root.Add(child, new XElement("房产", "30处"), new XElement("黄金", "10000000000000000.00万两"));

            StringWriter sw = new StringWriter();//实现一个用于将信息写入字符串的 TextWriter。该信息存储在基础 StringBuilder 中。 


            doc.Save(sw, SaveOptions.None);//将 XML 文档保存到指定的 XmlWriter。 
            sw.Close ();
            doc.Save("C://text.xml");
            Console.WriteLine(sw.ToString());
            Console.ReadKey();
        }
    }
}
使用Elements Descendants方法检索元素集合
    class Program
    {
        static void Main(string[] args)
        {
            string sxml = @"<根节点>
                                  <子节点>
                                        <第3级>1</第3级>
                                        <第3级>2</第3级>
                                   </子节点>
                                  <子节点>2</子节点>
                                  <子节点>3</子节点>
                                  <子节点>4</子节点>
                                  <子节点>5</子节点>
                                  <子节点>6</子节点>
                            </根节点>";

            XElement el = XElement.Parse(sxml);

            Console.WriteLine("应用Elements方法返回的子元素集合");
            IEnumerable<XElement> elChilds = el.Elements();
            foreach (XElement e in elChilds)
            {
                Console.WriteLine(e.Name.LocalName);
                Console.WriteLine(e.Value);//获取或设置此元素的名称。
                //Console.WriteLine(e.Name.Namespace);
            }
            Console.WriteLine("\n应用Descendants方法返回的子元素集合");
            IEnumerable<XElement> elChilds2 = el.Descendants();
            foreach (XElement e in elChilds2)
            {
                Console.WriteLine(e.Name.LocalName);
                Console.WriteLine(e.Value);
            }

            Console.ReadKey();
        }
    }
使用Ancestors AncestorsAndSelf方法检索父元素集合
class Program
    {
        static void Main(string[] args)
        {

            string sxml = @"<根节点>
                                  <子节点1>
                                        <第3级节点 />
                                  </子节点1>
                                  <子节点2 />
                                  <子节点3 />
                                  <子节点4 />
                            </根节点>";

            XElement el = XElement.Parse(sxml);

            XElement el2 = el.Descendants("第3级节点").First();

            Console.WriteLine("应用Ancestors方法返回父元素集合");
            foreach(XElement e in el2.Ancestors())
                Console.WriteLine(e.Name.LocalName);

            Console.WriteLine("\n应用AncestorsAndSelf方法返回父元素集合");
            foreach (XElement e in el2.AncestorsAndSelf())
                Console.WriteLine(e.Name.LocalName);


            Console.ReadKey();
        }
    }
使用ElementsAfterSelf ElementsBeforeSelf方法检索元素集合
class Program
    {
        static void Main(string[] args)
        {
            string sxml = @"<根节点>
                                  <子节点1 /> 
                                  <子节点2 />
                                  <Test子节点 />
                                  <子节点4 />
                                  <子节点5 />
                                  <子节点6 />
                            </根节点>";


            XElement el = XElement.Parse(sxml);

            IEnumerable<XElement> els = el.Element("Test子节点").ElementsAfterSelf();
            Console.WriteLine("应用ElementsAfterSelf方法返回的元素集合");
            foreach (XElement e in els)
                Console.WriteLine(e);

            IEnumerable<XElement> els2 = el.Element("Test子节点").ElementsBeforeSelf();
            Console.WriteLine("应用ElementsBeforeSelf方法返回的元素集合");
            foreach (XElement e in els2)
                Console.WriteLine(e);

            Console.ReadKey();
        }
检索获取元素的值
 class Program
    {
        static void Main(string[] args)
        {
            string sxml = @"<根节点>
                                  <子节点>1</子节点>
                                    <子节点>
                                        <第3级>1</第3级>
                                        <第3级>2</第3级>
                                    </子节点>
                                  <子节点2>2</子节点2>
                                  <子节点3>字符串值</子节点3>
                                  <子节点>4</子节点>
                            </根节点>";

            XElement el = XElement.Parse(sxml);

            Console.WriteLine("第一个子节点的值:{0}", el.Element("子节点").Value);

            string svalue = (string)(el.Element("子节点3")).Value ;
            Console.WriteLine("强制转换得到子节点3的值:{0}", svalue);

            int? ivalue = (int?)el.Element("不存在的节点");
            Console.WriteLine("可空类型的强制转换:{0}", ivalue == null ? "值为null" : ivalue.ToString());

            int ivalue2 = (int)el.Element("子节点2");
            Console.WriteLine("强制转换得到子节点2的值:{0}", ivalue2);

            el.Element("子节点2").Value = "字符串值";
            Console.WriteLine("子节点2的Value:{0}", el.Element("子节点2").Value);

            el.Element("子节点2").SetValue(12345);
            Console.WriteLine("子节点2的Value:{0}", el.Element("子节点2").Value);

            Console.ReadKey();
        }
    }
添加元素的轴方法 Add ...
 class Program
    {
        static void Main(string[] args)
        {
            XElement el = new XElement("根节点");

            el.Add(new XElement("Add添加的子节点"));

            el.Add(new XElement("Add添加的子节点"),
                new XElement("Add添加的子节点")
                );

            el.AddFirst(new XElement("AddFirst添加的子节点"));

            el.Element("AddFirst添加的子节点").AddAfterSelf(new XElement("AddAfterSelf添加的节点1"));

            el.Element("AddFirst添加的子节点").AddBeforeSelf(new XElement("AddBeforeSelf添加的节点2"));

            Console.WriteLine(el);

            Console.ReadKey();
        }
    }
删除元素的轴方法
class Program
    {
        static void Main(string[] args)
        {
            XElement el = new XElement("根节点");

            el.Add(new XElement("子节点1"),
                new XElement("子节点2"),
                new XElement("子节点3"),
                new XElement("子节点4")
                );

            el.Element("子节点3").Remove();

            Console.WriteLine(el);

            el.RemoveAll();

            Console.WriteLine("\n对根节点应用RemoveAll方法后");
            Console.WriteLine(el);
            Console.ReadKey();
        }
    }
ReplaceWith 方法替换元素
 class Program
    {
        static void Main(string[] args)
        {
            string sxml = @"<根节点>
                                  <子节点1 />
                                  <子节点2 />
                                  <子节点3 />
                                  <子节点4 />
                            </根节点>";

            XElement el = XElement.Parse(sxml);

            el.Element("子节点2").ReplaceWith(new XElement("原型一替换的"));
            Console.WriteLine("应用ReplaceWith原型一之后");
            Console.WriteLine(el);

            el.Element("子节点3").ReplaceWith(new XElement("替换3"), new XElement("新加入"));
            Console.WriteLine("\n应用ReplaceWith原型二之后");
            Console.WriteLine(el);

            Console.ReadKey();
        }
    }
使用SetElementValue处理子元素

LINQ to XML使用XAttribute类表示XML元素的属性

XAttribute
class Program
    {
        static void Main(string[] args)
        {
            XElement root = new XElement("根元素",
                new XAttribute("属性1", ""),
                new XAttribute("属性2", "0"));

            XElement child = new XElement("子元素1");
            child.Add(new XAttribute("子节点上的属性", "**"));

            XDocument doc = new XDocument(root);

            doc.Root.Add(child,
                new XElement("子元素2", "元素值"),
                new XElement("子元素3")
                );


            Console.WriteLine(doc);
            Console.ReadKey();
        }
使用Attributes方法获取元素的属性集合
class Program
    {
        static void Main(string[] args)
        {
            string sxml = @"<根节点>
                                  <子节点1 属性1='1' 属性2='测试' />
                                  <子节点2 />
                                  <子节点3 />
                                  <子节点4 />
                            </根节点>";

            XElement el = XElement.Parse(sxml);

            foreach( var a in el.Element("子节点1").Attributes())
                Console.WriteLine(a);

            Console.ReadKey();

        }
    }
使用Attribute方法获取元素的属性
 class Program
    {
        static void Main(string[] args)
        {
            string sxml = @"<根节点>
                                  <子节点1 属性1='1' 属性2='测试' />
                                  <子节点2 />
                                  <子节点3 />
                                  <子节点4 />
                            </根节点>";

            XElement el = XElement.Parse(sxml);

            Console.WriteLine(el.Element("子节点1").Attribute("属性2"));

            Console.WriteLine(el.Element("子节点1").Attribute("属性3") == null ? "属性3并不存在" : el.Element("子节点1").Attribute("属性3").ToString());

            Console.ReadKey();
        }
    }
使用ReplaceAttributes替换元素的属性
 class Program
    {
        static void Main(string[] args)
        {
            string sxml = @"<根节点>
                                  <子节点1 属性1='测试'/>
                                  <子节点2 />
                                  <子节点3 />
                                  <子节点4 />
                            </根节点>";

            XElement el = XElement.Parse(sxml);

            el.Element("子节点1").ReplaceAttributes(new XAttribute("原型一替换",0));
            Console.WriteLine("应用ReplaceAttributes原型一之后");
            Console.WriteLine(el.Element("子节点1"));

            el.Element("子节点1").ReplaceAttributes(new XAttribute("原型二替换",0), new XAttribute("原型二添加",0));
            Console.WriteLine("\n应用ReplaceAttributes原型二之后");
            Console.WriteLine(el.Element("子节点1"));

            Console.ReadKey();
        }
    }
使用RemoveAttributes删除元素的属性
    class Program
    {
        static void Main(string[] args)
        {
            string sxml = @"<根节点>
                                  <子节点1 属性1='测试' 属性2='0'>
                                         <第3级 属性='1'/>
                                   </子节点1>
                                  <子节点2 />
                            </根节点>";

            XElement el = XElement.Parse(sxml);

            Console.WriteLine("应用RemoveAttributes之后");

            el.Element("子节点1").RemoveAttributes();

            Console.WriteLine(el);

            el.Element("子节点1").RemoveAll();

            Console.WriteLine("\n应用RemoveAll之后");
            Console.WriteLine(el);
            Console.ReadKey();
        }
    }
使用SetAttributesValue处理元素的属性

LINQ to XML使用XComment类表示XML文档中的注释节点

XComment
class Program
    {
        static void Main(string[] args)
        {
            XElement root = new XElement("根元素",
                new XComment("这是根节点的注释内容"),
                new XAttribute("属性", "0"));

            XDocument doc = new XDocument(new XComment("这是文档的注释内容"),root);

            doc.Root.Add(new XElement("子元素", "元素值"),
                new XElement("子元素",new XComment ("子元素测试属性"),"段陶",new XAttribute ("属性","1"))
                );


            Console.WriteLine(doc);
            Console.ReadKey();
        }
    }

LINQ to XML 使用XDeclaration类表示一个XML声明

XDeclaration
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Text;

namespace DemoXDeclaration
{
    class Program
    {
        static void Main(string[] args)
        {
            XElement root = new XElement("根元素",
                new XAttribute("属性", "0"));

            XDocument doc = new XDocument(new XComment("这是文档的注释内容"), root);

            doc.Declaration = new XDeclaration("1.0", "utf-16", "yes");

            doc.Root.Add(new XElement("子元素"),
                new XElement("子元素")
                );

            StringWriter sw = new StringWriter();
            doc.Save(sw, SaveOptions.None);
            sw.Close();

            Console.WriteLine(sw.ToString());

            Console.ReadKey();
        }
    }
}

LINQ to XML使用XDoumentType类表示文档类型定义DTD

XDocumentType
class Program
    {
        static void Main(string[] args)
        {
            XElement root = new XElement("根元素",
               new XAttribute("属性", "0"));

            XDocument doc = new XDocument(
                new XDocumentType("限定名","Test Name","专用标识符","内部子集"),
                new XComment("这是文档的注释内容"), root);


            doc.Root.Add(new XElement("子元素"),
                new XElement("子元素")
                );

            Console.WriteLine(doc);

            Console.ReadKey();
        }

LINQ to XML使用XProcessingInstruction类,表示XML处理指令

XProcessingInstruction
class Program
    {
        static void Main(string[] args)
        {
            XElement root = new XElement("根元素",
               new XAttribute("属性", "0"));

            XDocument doc = new XDocument(
                new XProcessingInstruction ("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
                new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
                new XComment("这是文档的注释内容"), root);


            doc.Root.Add(new XElement("子元素"),
                new XElement("子元素")
                );

            Console.WriteLine(doc);

            Console.ReadKey();
        }
    }

LINQ to XML使用XCdata类,表示一个包含CDDATA的文本类型

XCData
class Program
    {
        static void Main(string[] args)
        {
            XElement root = new XElement("根元素",
           new XAttribute("属性", "0")
           );

            XDocument doc = new XDocument(
                new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
                new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
                new XComment("这是文档的注释内容"), root);


            root.Add(new XElement("子元素"),
                new XElement("子元素")
                );

            root.Add(new XCData("这里是根元素的CDATA节点"));

            Console.WriteLine(doc);

            Console.ReadKey();
        }
    }

LINQ to XML使用XNamespace类表示一个XML命名空间。

XNamespace
 class Program
    {
        static void Main(string[] args)
        {
            XNamespace sp = "http://www.tiyor.com";

            XElement root = new XElement(sp + "根元素",
              new XAttribute("属性", "0")
              );

            XDocument doc = new XDocument(
                new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
                new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
                new XComment("这是文档的注释内容"), root);


            root.Add(new XElement(sp + "子元素"),
                new XElement(sp + "子元素")
                );

            root.Add(new XCData("这里是根元素的CDATA节点"));

            Console.WriteLine(doc);

            Console.ReadKey();
           
        }
    }

 编写复杂LINQ表达式查询元素

View Code
class Program
    {
        static void Main(string[] args)
        {
            string sxml = @"<通讯录>
                              <客户 姓名='肖青漩' 年龄='21'>
                                 <职务>出云公主</职务>
                                 <电话>017*-876543**</电话>
                              </客户>
                              <客户 姓名='董巧巧' 年龄='19'>
                                 <职务>乖巧人儿</职务>
                                 <电话>029*-981256**</电话>
                              </客户>
                              <客户 姓名='萧玉霜' 年龄='17'>
                                 <职务>萧家二小姐</职务>
                                 <电话>053*-985690**</电话>
                              </客户>
                            </通讯录>";

            XElement root = XElement.Parse(sxml);

            //筛选年龄属性大于18的客户
            /*var query = from item in root.Elements("客户")
                        where (from att in item.Attributes()
                               where att.Name.LocalName == "年龄"
                               select att).Any(age=>(int)age>18)
                        select item;*/
            var query = from item in root.Elements("客户")
                        where (from att in item.Attributes() where att.Name.LocalName == "年龄" select att).Any(att => (int)att > 18)
                        select item;

            foreach (var el in query)
                Console.WriteLine(el);
           
            Console.ReadKey();
                                              
        }
    }

使用LINQ表达式对XML元素排序

View Code
 class Program
    {
        static void Main(string[] args)
        {
            string sxml = @"<通讯录>
                              <客户 姓名='肖青漩' 年龄='21'>
                                 <职务>出云公主</职务>
                                 <电话>017*-876543**</电话>
                              </客户>
                              <客户 姓名='董巧巧' 年龄='19'>
                                 <职务>乖巧人儿</职务>
                                 <电话>029*-981256**</电话>
                              </客户>
                              <客户 姓名='萧玉霜' 年龄='17'>
                                 <职务>萧家二小姐</职务>
                                 <电话>053*-985690**</电话>
                              </客户>
                              <客户 姓名='秦仙儿' 年龄='20'>
                                 <职务>霓裳公主</职务>
                                 <电话>023*-338987**</电话>
                              </客户>
                              <客户 姓名='萧玉若' 年龄='21'>
                                 <职务>萧家大小姐</职务>
                                 <电话>035*-120967**</电话>
                              </客户>
                              <客户 姓名='洛凝' 年龄='19'>
                                 <职务>金陵才女</职务>
                                 <电话>033*-985690**</电话>
                              </客户>
                            </通讯录>";

            XElement root = XElement.Parse(sxml);

            var query = from item in root.Elements("客户")
                        orderby (int)item.Attribute("年龄"), item.Element("电话").Value
                        select item;

            foreach (var el in query)
                Console.WriteLine(el);

            Console.ReadKey();
        }
    }

使用LINQ表达式计算XML元素

View Code
class Program
    {
        static void Main(string[] args)
        {
            string sxml = @"<通讯录>
                              <客户 姓名='肖青漩' 年龄='21'>
                                 <职务>出云公主</职务>
                                 <电话>017*-876543**</电话>
                                 <订货单>
                                     <品名>6克拉钻石戒指</品名>
                                     <单价>120,000</单价>
                                     <数量>3</数量>
                                 </订货单>
                                 <订货单>
                                     <品名>真丝旗袍</品名>
                                     <单价>3,600</单价>
                                     <数量>2</数量>
                                 </订货单>
                              </客户>
                              <客户 姓名='董巧巧' 年龄='19'>
                                 <职务>乖巧人儿</职务>
                                 <电话>029*-981256**</电话>
                                 <订货单>
                                     <品名>旺角酒楼</品名>
                                     <单价>2,500,000</单价>
                                     <数量>1</数量>
                                 </订货单>
                                 <订货单>
                                     <品名>奥迪TT</品名>
                                     <单价>650,000</单价>
                                     <数量>1</数量>
                                 </订货单>
                              </客户>
                              <客户 姓名='萧玉霜' 年龄='17'>
                                 <职务>萧家二小姐</职务>
                                 <电话>053*-985690**</电话>
                              </客户>
                              <客户 姓名='秦仙儿' 年龄='20'>
                                 <职务>霓裳公主</职务>
                                 <电话>023*-338987**</电话>
                                 <订货单>
                                     <品名>独门四合院</品名>
                                     <单价>12,000,000</单价>
                                     <数量>1</数量>
                                 </订货单>
                              </客户>
                              <客户 姓名='萧玉若' 年龄='21'>
                                 <职务>萧家大小姐</职务>
                                 <电话>035*-120967**</电话>
                              </客户>
                              <客户 姓名='洛凝' 年龄='19'>
                                 <职务>金陵才女</职务>
                                 <电话>033*-985690**</电话>
                              </客户>
                            </通讯录>";

           /* XElement root = XElement.Parse(sxml);

            var query = from item in root.Elements("客户")
                        let cc = (from l in item.Elements("订货单")//let语句用于在LINQ表达式中存储子表达式的计算结果。
                                  let c = Convert.ToDouble(l.Element("单价").Value) * (double)l.Element("数量")
                                  select c).Sum()
                        orderby cc descending
                        select new { Guest = item, Count = cc };

            foreach (var item in query)
            {
                Console.WriteLine("姓名:{0} 订单总价:{1}", item.Guest.Attribute("姓名").Value, item.Count.ToString());
                foreach (var p in item.Guest.Elements("订货单"))
                    Console.WriteLine("{0} {1} {2}", p.Element("品名").Value, p.Element("单价").Value, p.Element("数量").Value);
                Console.WriteLine("----------------------------------------------");
            }

            Console.ReadKey();*/
            XElement root = XElement.Parse(sxml);
            var query =from item in root.Elements("客户")
                       let cc=(from l in item.Elements ("订货单")
                               let c=Convert.ToDouble (l.Element ("单价").Value) *(double)l.Element("数量") select c).Sum() orderby cc descending 
                               select new {Guest=item ,Count=cc };
            foreach (var item in query)
            {
                Console.WriteLine("姓名:{0} 订单总价:{1}", item.Guest.Attribute("姓名").Value, item.Count.ToString());
                foreach (var p in item.Guest.Elements("订货单"))
                    Console.WriteLine("{0}  {1}  {2}", p.Element("单价").Value, p.Element("数量").Value, p.Element("品名").Value);

            }
            Console.ReadKey();
        }
    }

使用LINQ表达式剔除XML树种的元素

View Code
class Program
    {
        static void Main(string[] args)
        {
            string sxml = @"<通讯录>
                              <客户 姓名='肖青漩' 年龄='21'>
                                 <职务>出云公主</职务>
                                 <电话>017*-876543**</电话>
                                 <订货单>
                                     <品名>6克拉钻石戒指</品名>
                                     <单价>120,000</单价>
                                     <数量>3</数量>
                                 </订货单>
                                 <订货单>
                                     <品名>真丝旗袍</品名>
                                     <单价>3,600</单价>
                                     <数量>2</数量>
                                 </订货单>
                              </客户>
                              <客户 姓名='董巧巧' 年龄='19'>
                                 <职务>乖巧人儿</职务>
                                 <电话>029*-981256**</电话>
                                 <订货单>
                                     <品名>旺角酒楼</品名>
                                     <单价>2,500,000</单价>
                                     <数量>1</数量>
                                 </订货单>
                                 <订货单>
                                     <品名>奥迪TT</品名>
                                     <单价>650,000</单价>
                                     <数量>1</数量>
                                 </订货单>
                              </客户>
                              <客户 姓名='萧玉霜' 年龄='17'>
                                 <职务>萧家二小姐</职务>
                                 <电话>053*-985690**</电话>
                              </客户>
                              <客户 姓名='秦仙儿' 年龄='20'>
                                 <职务>霓裳公主</职务>
                                 <电话>023*-338987**</电话>
                                 <订货单>
                                     <品名>独门四合院</品名>
                                     <单价>12,000,000</单价>
                                     <数量>1</数量>
                                 </订货单>
                              </客户>
                              <客户 姓名='萧玉若' 年龄='21'>
                                 <职务>萧家大小姐</职务>
                                 <电话>035*-120967**</电话>
                              </客户>
                              <客户 姓名='洛凝' 年龄='19'>
                                 <职务>金陵才女</职务>
                                 <电话>033*-985690**</电话>
                              </客户>
                            </通讯录>";

           /* XElement root = XElement.Parse(sxml);

            //剔除订单总价等于0的客户
            (from item in root.Elements("客户")
             let cc = (from l in item.Elements("订货单")
                       let c = Convert.ToDouble(l.Element("单价").Value) * (double)l.Element("数量")
                       select c).Sum()
             where cc == 0
             select item).Remove();

            //剔除XML树中的订单
            (from item in root.Elements("客户")
               from l in item.Elements("订货单")   
             select l).Remove();

            Console.WriteLine(root);
          
            Console.ReadKey();*/
            XElement root = XElement.Parse(sxml);
            Console.WriteLine(root);
            Console.WriteLine("*********************************************");
            (from item in root.Elements("客户")
             let cc = (from l in item.Elements("订货单")
                       let c = Convert.ToDouble(l.Element("单价").Value) * (double)l.Element("数量")
                       select c).Sum()
             where cc == 0
             select item).Remove();
            Console.WriteLine(root);
            Console.WriteLine("*********************************************");
            (from items in root.Elements("客户")
             from ls in items.Elements("订货单")
             select ls).Remove();
            Console.WriteLine(root);
            Console.ReadKey();
        }
    }

使用LINQ表达式变造XML树

View Code
class Program
    {
        static void Main(string[] args)
        {
            string sxml = @"<通讯录>
                              <客户 姓名='肖青漩' 年龄='21'>
                                 <职务>出云公主</职务>
                                 <电话>017*-876543**</电话>
                                 <订货单>
                                     <品名>6克拉钻石戒指</品名>
                                     <单价>120,000</单价>
                                     <数量>3</数量>
                                 </订货单>
                                 <订货单>
                                     <品名>真丝旗袍</品名>
                                     <单价>3,600</单价>
                                     <数量>2</数量>
                                 </订货单>
                              </客户>
                              <客户 姓名='董巧巧' 年龄='19'>
                                 <职务>乖巧人儿</职务>
                                 <电话>029*-981256**</电话>
                                 <订货单>
                                     <品名>旺角酒楼</品名>
                                     <单价>2,500,000</单价>
                                     <数量>1</数量>
                                 </订货单>
                                 <订货单>
                                     <品名>奥迪TT</品名>
                                     <单价>650,000</单价>
                                     <数量>1</数量>
                                 </订货单>
                              </客户>
                              <客户 姓名='萧玉霜' 年龄='17'>
                                 <职务>萧家二小姐</职务>
                                 <电话>053*-985690**</电话>
                              </客户>
                              <客户 姓名='秦仙儿' 年龄='20'>
                                 <职务>霓裳公主</职务>
                                 <电话>023*-338987**</电话>
                                 <订货单>
                                     <品名>独门四合院</品名>
                                     <单价>12,000,000</单价>
                                     <数量>1</数量>
                                 </订货单>
                              </客户>
                              <客户 姓名='萧玉若' 年龄='21'>
                                 <职务>萧家大小姐</职务>
                                 <电话>035*-120967**</电话>
                              </客户>
                              <客户 姓名='洛凝' 年龄='19'>
                                 <职务>金陵才女</职务>
                                 <电话>033*-985690**</电话>
                              </客户>
                            </通讯录>";

            XElement root = XElement.Parse(sxml);

            //统计结果
            var count = from item in root.Elements("客户")
                        let cc = (from l in item.Elements("订货单") let c = Convert.ToDouble(l.Element("单价").Value) * (double)l.Element("数量") select c).Sum()
                        where cc > 0
                        select new { Count = cc, Node = item };

            ///变造新的XML树
            XElement newroot = new XElement
                (
                "客户订单表",
                new XElement("订单总价", count.Sum(item => item.Count).ToString()),
                new XElement("订户总数", count.Count()),
                new XElement("明细",
                                    (from i in count
                                     select new XElement(i.Node.Name, i.Node.Attribute("姓名"),
                                                         new XAttribute("电话", i.Node.Element("电话").Value),
                                                         new XAttribute("小计", i.Count.ToString()),
                                                         (from p in i.Node.Elements("订货单") select new XElement("订货", from l in p.Elements() select new XAttribute(l.Name, l.Value)))))
                              )
                );

            Console.WriteLine(newroot);

            Console.ReadKey();
        }
    }

使用LINQ查询运算符变造XML树

View Code
class Program
    {
        static void Main(string[] args)
        {
            string sxml = @"<数据>
                                <字>你 赵 月 钱 李 王 孙 喜 晨 曦 我 凡 宝 悦 爱</字>
                                <数>2 3 4 5 6 7</数>
                                <颜色>粉 绿 黄 兰</颜色>
                                <其他>蛋糕 妈妈 衣服</其他>
                            </数据>";

            XElement root = XElement.Parse(sxml);

            ///变造新的XML树
            XElement newroot = new XElement
                (
                new XElement("我的宝贝",
                    new XElement("姓名",
                        string.Format("{0}{1}{2}",
                        root.Element("").Value.Split(' ').ElementAt(1),
                        root.Element("").Value.Split(' ').ElementAt(8),
                        root.Element("").Value.Split(' ').ElementAt(9))),
                     new XElement("乳名",
                         string.Format("{0}{1}",
                        root.Element("").Value.Split(' ').ElementAt(12),
                        root.Element("").Value.Split(' ').ElementAt(12))),
                     new XElement("年龄",
                         string.Format("{0}岁",
                        root.Element("").Value.Split(' ').ElementAt(1))),
                    new XElement("喜欢的颜色",
                         string.Format("{0}色",
                        root.Element("颜色").Value.Split(' ').First())),
                     new XElement("喜欢的食物",
                         root.Element("其他").Value.Split(' ').First()),
                     new XElement("最喜欢的人",
                         root.Element("其他").Value.Split(' ').ElementAt(1)),
                     new XElement("经常说的话", 
                         string.Format("{0}{1}{2}{3}",
                         root.Element("其他").Value.Split(' ').ElementAt(1),
                         root.Element("").Value.Split(' ').ElementAt(10),
                         root.Element("").Value.Split(' ').Last(),
                         root.Element("").Value.Split(' ').First())),
                      new XElement("依恋物", 
                         string.Format("{0}{1}",
                         root.Element("其他").Value.Split(' ').ElementAt(1),
                         root.Element("其他").Value.Split(' ').Last()))
                     )
                   );


            Console.WriteLine(newroot);

            Console.ReadKey();

        }
    }

XML输出到字符串

View Code
 class Program
    {
        static void Main(string[] args)
        {
             XNamespace sp = "http://www.tiyor.com";

            XElement root = new XElement(sp + "根元素",
              new XAttribute("属性", "0")
              );

            XDocument doc = new XDocument(
                new XDeclaration("1.0","utf-16","yes"),
                new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
                new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
                new XComment("这是文档的注释内容"), root);


            root.Add(new XElement(sp + "子元素"),
                new XElement(sp + "子元素")
                );

            root.Add(new XCData("这里是根元素的CDATA节点"));

            StringWriter strw = new StringWriter();
            doc.Save(strw, SaveOptions.None);
            strw.Close();

            string strxml = strw.ToString();

            Console.WriteLine(strxml);

            Console.ReadKey();
        }
    }

XML输出大片TextWriter

View Code
class Program
    {
        static void Main(string[] args)
        {
            XNamespace sp = "http://www.tiyor.com";

            XElement root = new XElement(sp + "根元素",
              new XAttribute("属性", "0")
              );

            XDocument doc = new XDocument(
                new XDeclaration("1.0", "utf8", "yes"),
                new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
                new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
                new XComment("这是文档的注释内容"), root);


            root.Add(new XElement(sp + "子元素"),
                new XElement(sp + "子元素")
                );

            root.Add(new XCData("这里是根元素的CDATA节点"));
            //Console.Out属性提供TextWriter对象
            doc.Save(Console.Out, SaveOptions.None);
            Console.ReadKey();
        }
    }

XML输出到文件

View Code
class Program
    {
        static void Main(string[] args)
        {
            XNamespace sp = "http://www.tiyor.com";

            XElement root = new XElement(sp + "根元素",
              new XAttribute("属性", "0")
              );

            XDocument doc = new XDocument(
                new XDeclaration("1.0", "utf8", "yes"),
                new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
                new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
                new XComment("这是文档的注释内容"), root);


            root.Add(new XElement(sp + "子元素"),
                new XElement(sp + "子元素")
                );

            root.Add(new XCData("这里是根元素的CDATA节点"));

            
            doc.Save("test1.xml", SaveOptions.None);
            XmlWriter xw = XmlWriter.Create("test2.xml");
            doc.WriteTo(xw);
            xw.Close();

        }
    }

注:本文代码来自《LINQ入门及应用》!!!

原文地址:https://www.cnblogs.com/YuanSong/p/2621230.html