那天有个小孩跟我说LINQ(七)转载

1  LINQ TO XML(代码下载)

       准备:新建项目 linq_Ch7控制台程序,新建一个XML文件夹,我们就轻松地学习一下吧

         XDocument         创建XML文档

         XDeclaration       创建XML中的声明

         XElement             创建XML中的元素

         XAttribute            创建XML中元素的属性

         XComment           创建XML中的注释

 

 

1.1 创建与读取XML文件

           ①创建XML

              代码如下:

   1:   #region 创建一个XML文件夹
   2:              string dir = Environment.CurrentDirectory + @"/XML";
   3:              if (!Directory.Exists(dir))
   4:              {
   5:                  Directory.CreateDirectory(dir);
   6:              }
   7:              #endregion
   8:              string filePath1 = Environment.CurrentDirectory + @"/XML/XML1.xml";
   9:              #region 创建一个xml
  10:              //创建一个xml文档
  11:              XDocument doc1 = new XDocument(
  12:                  //创建一个声明
  13:                     new XDeclaration("1.0", "utf-8", "yes"),
  14:                     new XElement("Products",
  15:                                     new XAttribute("KeyName", "ID"),
  16:                                     new XAttribute("Identity", "true"),
  17:                                     new XAttribute("IdentitySeed", "1"),
  18:                                     new XAttribute("IdentityIncrement", "1"), new XComment("ID是产品表中的主键"),
  19:                                     new XElement("Product", new XAttribute("ID", "1"),
  20:                                            new XElement("ID", "1", new XComment("编号"), new XAttribute("type", "int")),
  21:                                            new XElement("ProductCode", "XYBCNSZYXMN", new XComment("产品编号"), new XAttribute("type", "nvarchar(50)")),
  22:                                            new XElement("ProductName", "相宜本草男士专用洗面奶", new XComment("产品名称"), new XAttribute("type", "nvarchar(50)")),
  23:                                            new XElement("ProductUnitPrice", "39.90", new XComment("产品单价"), new XAttribute("type", "decimal(18,2)")),
  24:                                            new XElement("ProductTypeID", "1", new XComment("产品类型"), new XAttribute("type", "smallint"),
  25:                                                    new XAttribute("ForeignTable", "ProductType"),
  26:                                                    new XAttribute("ForeignTableColumn", "ID")
  27:                                            ),
  28:                                            new XElement("ProductDescription", "祛痘效果很好", new XComment("产品描述"), new XAttribute("type", "nvarchar(200)"))
  29:                              )
  30:                         )
  31:                  );
  32:              doc1.Save(filePath1);
  33:              Console.WriteLine("创建成功");
  34:              #endregion

效果图:image

生成XML文件内容如下:

image

②读取XML

   1:              #region 读取
   2:              XElement doc2 = XElement.Load(filePath1);
   3:              Console.WriteLine(doc2.ToString());
   4:              #endregion

效果图:

image

 

1.2 查找基础

     1.2.1 根元素

            XDocument doc3 = XDocument.Load(filePath1);
            //根元素
            Console.WriteLine("根元素:" + doc3.Root.Name);

     1.2.2 查找指定名称的元素

   1:              //查找指定名称的元素
   2:              IEnumerable<XElement> elements1 = from xml in doc2.Elements("Product")
   3:                                                where xml.Element("ID").Value == "1"
   4:                                                select xml;
   5:              foreach (XElement xe in elements1)
   6:              {
   7:                  Console.WriteLine(xe.Name.LocalName + ":" + xe.Attribute("ID").Value);
   8:              }

     效果图:

     image

    1.2.3 查找指定属性的元素

     我们再添加几个Product

   1:  <?xml version="1.0" encoding="utf-8" standalone="yes"?>
   2:  <Products KeyName="ID" Identity="true" IdentitySeed="1" IdentityIncrement="1">
   3:    <!--ID是产品表中的主键-->
   4:    <Product ID="1">
   5:      <ID type="int">1<!--编号--></ID>
   6:      <ProductCode type="nvarchar(50)">XYBCNSZYXMN<!--产品编号--></ProductCode>
   7:      <ProductName type="nvarchar(50)">相宜本草男士专用洗面奶<!--产品名称--></ProductName>
   8:      <ProductUnitPrice type="decimal(18,2)">39.90<!--产品单价--></ProductUnitPrice>
   9:      <ProductTypeID type="smallint" ForeignTable="ProductType" ForeignTableColumn="ID">1<!--产品类型--></ProductTypeID>
  10:      <ProductDescription type="nvarchar(200)">祛痘效果很好<!--产品描述--></ProductDescription>
  11:    </Product>
  12:      <Product ID="2">
  13:      <ID type="int">2<!--编号--></ID>
  14:      <ProductCode type="nvarchar(50)">
  15:        WP7CXSJ<!--产品编号--></ProductCode>
  16:      <ProductName type="nvarchar(50)">
  17:        Windows Phone7 程序设计<!--产品名称--></ProductName>
  18:      <ProductUnitPrice type="decimal(18,2)">
  19:        99.00<!--产品单价--></ProductUnitPrice>
  20:      <ProductTypeID type="smallint" ForeignTable="ProductType" ForeignTableColumn="ID">2<!--产品类型--></ProductTypeID>
  21:      <ProductDescription type="nvarchar(200)">
  22:        wp7开发必备<!--产品描述--></ProductDescription>
  23:    </Product>
  24:  </Products>

 开始查询:

   1:    //3.查找指定属性的元素
   2:              var elements2 = from xml in doc2.Elements("Product") //获得所有的Product节点
   3:                                          select new
   4:                                          {
   5:                                              编号 = xml.Element("ID").Value,
   6:                                              产品编号 = xml.Element("ProductCode").Value,
   7:                                              产品名称 = xml.Element("ProductName").Value,
   8:                                              产品单价 = xml.Element("ProductUnitPrice").Value,
   9:                                              产品类型ID = xml.Element("ProductTypeID").Value,
  10:                                              产品描述 = xml.Element("ProductDescription").Value
  11:                                          };
  12:              foreach (var item in elements2)
  13:              {
  14:                  Console.WriteLine("产品名称\t"+item.产品名称);
  15:              }
  16:              string ProductID="1";
  17:              //查找指定属性的元素
  18:              var elements3=from xml in doc2.Elements("Product")
  19:                                      where xml.Attribute("ID").Value==ProductID
  20:                                        select new
  21:                                        {
  22:                                            编号 = xml.Element("ID").Value,
  23:                                            产品编号 = xml.Element("ProductCode").Value,
  24:                                            产品名称 = xml.Element("ProductName").Value,
  25:                                            产品单价 = xml.Element("ProductUnitPrice").Value,
  26:                                            产品类型ID = xml.Element("ProductTypeID").Value,
  27:                                            产品描述 = xml.Element("ProductDescription").Value
  28:                                        };
  29:              foreach (var item in elements3)
  30:              {
  31:                   Console.WriteLine("ID为"+ProductID+"的产品名称为"+item.产品名称);
  32:              }

效果图:

image

在这里,我的第二个ProductName换行显示了,原因是xml文件中,这一个节点的内容是 换行显示的

 

1.2.4 访问指定元素的所有属性 

          XElement.FirstAttribute:获取此元素的第一个属性

          XElement.NextAttribute:  获取父元素的下一个属性

          代码如下:

   1:        //4.访问指定元素的所有属性
   2:              XAttribute firstAttr = doc2.FirstAttribute;
   3:              //如果第一个不为空,我们继续查找下一个属性
   4:              if (firstAttr != null) {
   5:                  Console.WriteLine(firstAttr.Name.LocalName+":"+firstAttr.Value);
   6:                  XAttribute nextAttr = firstAttr.NextAttribute;
   7:                  while (nextAttr!=null)
   8:                  {
   9:                      Console.WriteLine(nextAttr.Name.LocalName + ":" + nextAttr.Value);
  10:                      nextAttr = nextAttr.NextAttribute;
  11:                  }
  12:              }

效果图:

image

 

1.2.5 查找XML中指定名称的元素

          XContainer类(XDocument的父类)的Descendants(XName name)

          Descendants方法用于按文档顺序返回此文档或元素的经过筛选的自带元素的集合,集合中只包括具有匹配XName的元素

   1:     //5.查找XML中指定名称的元素
   2:              IEnumerable<XElement> elements4 = from xml in doc2.Descendants("ProductName")
   3:                                                                         select xml;
   4:              foreach (var item in elements4)
   5:              {
   6:                  Console.WriteLine(item.Name+":"+item.Value);
   7:              }

效果图:

image

 

 

1.2.6 遍历指定节点下的所有对象

   1:    //6.遍历指定节点下的所有对象
   2:              IEnumerable<XNode> nodes = doc2.Elements("Product").Nodes();
   3:              foreach (XNode item in nodes)
   4:              {
   5:                  Console.WriteLine(item.ToString());
   6:              }

效果图:

image

1.2.6 使用OfType<T> 筛选返回指定节点下的T

       返回注释XComment

   1:       IEnumerable<XComment> cmts = doc2.Elements("Product").Elements("ProductCode").Nodes().OfType<XComment>();
   2:              foreach (XComment item in cmts)
   3:              {
   4:                  Console.WriteLine(item.ToString());
   5:              }

效果图:

image

1.2.7 访问指定节点的父元素

   1:   
   2:              //7访问指定节点的父元素
   3:              string proname = "相宜本草男士专用洗面奶";
   4:              XElement elements6 = doc2.Descendants("ProductName").Where(itm => itm.Value == (proname)).First();
   5:              //获得它上面的父元素
   6:              XElement xe = elements6.Parent;
   7:              Console.WriteLine("《"+proname+"》对应的编码为"+xe.Element("ProductCode").Value);

效果图:

image

 

1.2.8 按元素名称排序

   1:   //8 .排序
   2:              var xx = from xml in doc2.Elements("Product")
   3:                       orderby xml.Element("ProductName").Value
   4:                       select new
   5:                       {
   6:                           产品名称=xml.Element("ProductName").Value,
   7:                           产品单价 = xml.Element("ProductUnitPrice").Value
   8:                       };
   9:              foreach (var item in xx)
  10:              {
  11:                  Console.WriteLine(item.产品名称+":"+item.产品单价+"元");
  12:              }

效果图:

image

 

1.2.9 使用Ancestors

代码:

   1:    //9.Ancestors的使用
   2:              IEnumerable<XElement> elements8 = from xml in doc2.Descendants("ProductName")
   3:                                                                         select xml;
   4:              Console.WriteLine("原来的元素");
   5:              foreach (XElement item in elements8)
   6:              {
   7:                  Console.WriteLine(item.Name + ":" + item.Value);
   8:              }
   9:              //显示每个元素的父元素
  10:              Console.WriteLine("现在的父元素");
  11:              foreach (XElement item in elements8.Ancestors())
  12:              {
  13:                   Console.WriteLine(item.Name + ":" + item.Value);
  14:              }

效果图:

image

返回元素集合中每个元素的所有属性,使用Attributes的使用

继续添加代码:

   foreach (XElement item in elements8.Ancestors())
            {
                 Console.WriteLine(item.Name + ":" + item.Value);
            }

效果图:

image

返回节点集合中每个节点的所有下级节点

继续添加代码

   1:             //返回节点集合中每个节点的所有下级节点
   2:              Console.WriteLine("返回节点集合中每个节点的所有下级节点");
   3:              foreach (XNode item in elements8.DescendantNodes())
   4:              {
   5:                  Console.WriteLine(item.ToString());
   6:              }

效果图:

image

 

 

 

 

1.3 操作基础

     1.3.1 添加元素到XML文件中去

   1:   //3.1
   2:              XElement newe = new XElement("Product", new XAttribute("ID", "3"),
   3:                                     new XElement("ID", "3", new XComment("编号"), new XAttribute("type", "int")),
   4:                                     new XElement("ProductCode", "DBTNT", new XComment("产品编号"), new XAttribute("type", "nvarchar(50)")),
   5:                                     new XElement("ProductName", "大白兔奶糖", new XComment("产品名称"), new XAttribute("type", "nvarchar(50)")),
   6:                                     new XElement("ProductUnitPrice", "19.90", new XComment("产品单价"), new XAttribute("type", "decimal(18,2)")),
   7:                                     new XElement("ProductTypeID", "2", new XComment("产品类型"), new XAttribute("type", "smallint"),
   8:                                             new XAttribute("ForeignTable", "ProductType"),
   9:                                             new XAttribute("ForeignTableColumn", "ID")
  10:                                     ),
  11:                                     new XElement("ProductDescription", "浓浓的奶香", new XComment("产品描述"), new XAttribute("type", "nvarchar(200)"))
  12:                       );
  13:              doc2.Add(newe);
  14:              doc2.Save(filePath1);
  15:              Console.WriteLine("添加元素成功!");

效果图:image

xml文件图:

   1:  <?xml version="1.0" encoding="utf-8"?>
   2:  <Products KeyName="ID" Identity="true" IdentitySeed="1" IdentityIncrement="1">
   3:    <!--ID是产品表中的主键-->
   4:    <Product ID="1">
   5:      <ID type="int">1<!--编号--></ID>
   6:      <ProductCode type="nvarchar(50)">XYBCNSZYXMN<!--产品编号--></ProductCode>
   7:      <ProductName type="nvarchar(50)">相宜本草男士专用洗面奶<!--产品名称--></ProductName>
   8:      <ProductUnitPrice type="decimal(18,2)">39.90<!--产品单价--></ProductUnitPrice>
   9:      <ProductTypeID type="smallint" ForeignTable="ProductType" ForeignTableColumn="ID">1<!--产品类型--></ProductTypeID>
  10:      <ProductDescription type="nvarchar(200)">祛痘效果很好<!--产品描述--></ProductDescription>
  11:    </Product>
  12:    <Product ID="2">
  13:      <ID type="int">2<!--编号--></ID>
  14:      <ProductCode type="nvarchar(50)">WP7CXSJ<!--产品编号--></ProductCode>
  15:      <ProductName type="nvarchar(50)">Windows Phone7 程序设计</ProductName>
  16:      <ProductUnitPrice type="decimal(18,2)">99.00<!--产品单价--></ProductUnitPrice>
  17:      <ProductTypeID type="smallint" ForeignTable="ProductType" ForeignTableColumn="ID">2<!--产品类型--></ProductTypeID>
  18:      <ProductDescription type="nvarchar(200)">wp7开发必备<!--产品描述--></ProductDescription>
  19:    </Product>
  20:    <Product ID="3">
  21:      <ID type="int">3<!--编号--></ID>
  22:      <ProductCode type="nvarchar(50)">DBTNT<!--产品编号--></ProductCode>
  23:      <ProductName type="nvarchar(50)">大白兔奶糖<!--产品名称--></ProductName>
  24:      <ProductUnitPrice type="decimal(18,2)">19.90<!--产品单价--></ProductUnitPrice>
  25:      <ProductTypeID type="smallint" ForeignTable="ProductType" ForeignTableColumn="ID">2<!--产品类型--></ProductTypeID>
  26:      <ProductDescription type="nvarchar(200)">浓浓的奶香<!--产品描述--></ProductDescription>
  27:    </Product>
  28:  </Products>

1.3.2 修改XML元素和属性

   1:    IEnumerable<XElement> elements9 = from xml in doc2.Elements("Product")
   2:                                                where xml.Element("ID").Value == "1"
   3:                                                && xml.Element("ProductTypeID").Value == "1"
   4:                                                select xml;
   5:              if (elements9.Count() > 0) {
   6:                  XElement one = elements9.FirstOrDefault();
   7:                  one.SetElementValue("ProductName", "第一个产品");
   8:                  one.SetAttributeValue("ID", "7");
   9:              }
  10:              doc2.Save(filePath1);
  11:              Console.WriteLine("修改元素属性和节点成功!");

效果图:

image修改成功!

1.3.3 替换指定节点下的所有元素

   1:     //3.3
   2:              IEnumerable<XElement> elements10 = from xml in doc2.Elements("Product")
   3:                                                 where xml.Element("ID").Value == "1"
   4:                                                 && xml.Element("ProductTypeID").Value == "1"
   5:                                                 select xml;
   6:              if (elements10.Count() > 0)
   7:              {
   8:                  XElement one = elements10.First();
   9:                  one.ReplaceAll(
  10:                      new XAttribute("ID", "1"),
  11:                      new XElement("ProductName", "相宜本草男士专用洗面奶", new XComment("产品名称"), new XAttribute("type", "nvarchar(50)")),
  12:                      new XElement("ProductTypeID", "2")
  13:                      );
  14:              }
  15:              doc2.Save(filePath1);
  16:              Console.WriteLine("替换元素属性和节点成功!");

效果图:

image

1.3.4 删除XML中的元素

         使用XElement.Remove()方法,可以删除节点

1.3.5 合计XML元素值

        我们先把Product ID=”1”的那个Product,添加一个ProductUnitPrice节点,方便累加

       image

       然后我们写代码

   1:     //3.5
   2:              IEnumerable<XElement> elements11 = from ee in doc2.Elements("Product")
   3:                                                                             select ee;
   4:              decimal sums = elements11.Sum(i => Convert.ToDecimal(i.Element("ProductUnitPrice").Value));
   5:              Console.WriteLine("累加后的产品总价为"+sums);

      效果图:

      image

 

 

1.4 属性操作

       1.4.1 添加

   1:    IEnumerable<XElement> elements12 = from xml in doc2.Elements("Product")
   2:                                                 where xml.Attribute("ID").Value == "1"
   3:                                                 select xml;
   4:              XAttribute xa = new XAttribute("Increaments", "每次增长的值的大小");
   5:              if (elements12.Count() > 0) {
   6:                  XElement xles = elements12.FirstOrDefault();
   7:                  xles.Add(xa);
   8:              }
   9:              doc2.Save(filePath1);
  10:              Console.WriteLine("添加元素属性成功!");

        效果图:image

        XML文件内容:

        image

      1.4.2 修改

   1:            if (elements12.Count() > 0)
   2:              {
   3:                  XElement xles = elements12.FirstOrDefault();
   4:                  xles.Attribute("Increaments").Value="每次增长的值的大小已经被我修改了";
   5:              }
   6:              doc2.Save(filePath1);
   7:              Console.WriteLine("修改元素属性成功!");

       效果图:image

       XML文件内容:

      image

       1.4.3 删除,同元素一样,获得后XAttribute后.Remove()就可以删除

       1.4.4 删除一个元素上的所有属性,获得XElement后.RemoveAttributes()就可以删除一个元素上的所有属性

     

 

1.5 其他操作

    1.5.1 添加注释到XMl文件

   1:    IEnumerable<XElement> elements13 = from xml in doc2.Elements("Product")
   2:                                                 where xml.Attribute("ID").Value == "1"
   3:                                                 select xml;
   4:              //添加注释到xml文件
   5:              if (elements13.Count() > 0) {
   6:                  XElement xelements = elements13.FirstOrDefault();
   7:                  XComment comx = new XComment("这是我测试的注释2013年4月13日1:10:28");
   8:                  xelements.AddFirst(comx);
   9:              }
  10:              doc2.Save(filePath1);
  11:              Console.WriteLine("添加注释到xml成功!");

    XML文件内容如下:

   image

1.5.2添加声明到XML文件中

XDocument doc5 = new XDocument(
                new XDeclaration("1.0","utf-8","yes"),
                new XElement("People","茗洋芳竹")
                );
            doc5.Save(Environment.CurrentDirectory+@"\XML\xml2.xml");
            Console.WriteLine("添加了一个声明的XML创建成功");

效果图:

image

 

1.5.3添加文档类型到XML文件中(XDocumentType)

   1:   XDocument doc6 = new XDocument(
   2:                  new XDocumentType("People",null, "People.dtd",null),
   3:                  new XElement("People", "茗洋芳竹")
   4:                  );
   5:              doc6.Save(Environment.CurrentDirectory + @"\XML\xml3.xml");
   6:              Console.WriteLine("添加了一个文档类型的XML创建成功");

效果图:

image

1.5.4 给你一个字符串,变成一个XMl对象

   1:   string xmlStr = "<Product ID=\"2\"><ID type=\"int\">2<!--编号--></ID><ProductCode type=\"nvarchar(50)\">WP7CXSJ<!--产品编号--></ProductCode>"
   2:  +"<ProductName type=\"nvarchar(50)\">Windows Phone7 程序设计</ProductName>"
   3:     +" <ProductUnitPrice type=\"decimal(18,2)\">99.00<!--产品单价--></ProductUnitPrice>"
   4:      +"<ProductTypeID type=\"smallint\" ForeignTable=\"ProductType\" ForeignTableColumn=\"ID\">2<!--产品类型--></ProductTypeID>"
   5:      +"<ProductDescription type=\"nvarchar(200)\">wp7开发必备<!--产品描述--></ProductDescription>"
   6:    +"</Product>";
   7:              XElement txe = XElement.Parse(xmlStr);
   8:              txe.Save(Environment.CurrentDirectory+@"\XML\xml5.xml");

效果图:

image

 

1.5.5 使用Linq to XMl 转换XML

这里我直接贴代码了,使用linq to sql取出数据库数据,转换成XElement等对象。例如:

XDocument doc=new  XDocument(

         new XDeclaration(“1.0”,”utf-8”,”yes”),

         new XElement(“Products”,

                  from o in db.Products

                  select new XElement[]{

                      new XElement(“Product”,

                           new XAttribute(“ID”,o.ID),

                           new XElement(“ID”,o.ID),

                           new XElement(“ProductCode”,o.ProductCode),

                           …

                          )

}

聪明的你应该已经看懂了,这里只是一个思路

 

 

 

好了,到此为止,恭喜你,Linq to XML 你已经学习完了,谢谢你的学习!

posted @ 2013-07-02 21:27  小丑鱼1  阅读(303)  评论(0编辑  收藏  举报