• Linq学习<四> linq to XML


    LINQ to XML并不打算替代标准的XML API,例如,XML DOM(Document Object Model)、Path、XQuery和XSLT等。如果熟悉这些API或当前需要使用或学习它们,可以继续使用或学习。LINQ to XML补充了这些标准XML类,更便于使用XML。LINQ to XML为创建和查询XML据提供了额外的选项,代码更简单,开发许多常见的情形时速度更快,如果已经在其他程序中使了LINQ,开发速度将会更快。

    要使linq操作Xml 必须引入using System.Xml.Linq;命名空间

    下面我们比较几个创建xml文档的方法:

    1:传统运用xml api创建xml

    public void GeneratorXmlFile()
            {
                    string filePath = "../../xmlFile.xml";
                    XmlDocument xmldoc = new XmlDocument();
                    xmldoc.Load(filePath);                                           //load xml file
                 
                    XmlElement root = xmldoc.DocumentElement;                          //get root element
    
                    XmlNode node = root.LastChild;                                       //get last node
                    int number = int.Parse(node.ChildNodes[0].InnerText.ToString());   //get id of last node
    
                 
                    XmlElement customers = xmldoc.CreateElement("customers");           //create new element
                    XmlElement customer = xmldoc.CreateElement("custom");
                    XmlElement customerId = xmldoc.CreateElement("id");
                    XmlElement customerName = xmldoc.CreateElement("name");
                    XmlElement customerAge = xmldoc.CreateElement("age");
    
                    customerId.InnerText =( number+1).ToString();                       //number plus q
                    customerName.InnerText = "fj";
                    customerAge.InnerText = "22";
    
                    customer.AppendChild(customerId);                                    //append child
                    customer.AppendChild(customerName);
                    customer.AppendChild(customerAge);
                    root.InsertAfter(customer,root.LastChild);                          //append to root
                    xmldoc.Save(filePath);                                              //save file
            }
    

      2.利用XDocment参数列表的方式

    public void GeneratorAXmlDoc()
            {
                XDocument xdoc = new XDocument(
                     new XElement("customers",
                          new XElement("custome",
                              new XAttribute("color","red"),
                              new XAttribute("size","18px"),
                              new XElement("id",1
                                  )
                              ),
                           new XElement("custome",
                              new XAttribute("color", "black"),
                              new XAttribute("size", "30px"),
                              new XElement("id", 2
                                  )
                              )
                         )
                    );
                string filePath = "../../linqXml.xml";
                if (!File.Exists(filePath))
                { 
                 File.Create(filePath);
                }
                   
                xdoc.Save(filePath);
            }
    

      3.利用XDocument.parse静态方法

     public void GeneratorAXmlByXmlDocParse()
            {
                XDocument xDoc = XDocument.Parse
              (@"<?xml version=""1.0"" encoding=""utf-8""?>
                        <customers>
                            <custome color=""red"" size=""18px"">
                                     <id>1</id>
                            </custome>
                            <custome color=""black"" size=""30px"">
                                     <id>2</id>
                            </custome>
                        </customers>"
              
              );
                Console.WriteLine(xDoc);  //save an red function is the same as  GeneratorAXmlDoc and ReadLinqXmlfile
            }
    

      后两种方法的读取方法如下:

       public void ReadLinqXmlFile()
            {
                XDocument xdoc = XDocument.Load("../../linqXml.xml");
                Console.WriteLine(xdoc);
            }
    

      比较着三种方法,很显然用linq操作xml是很方便的。

          另外在linq中海能操作代码片段,能够导出数据库的数据成xml格式

    例子如下:

    1.创建代码片段,正常情况下,我们的xml都是从xmldoucment开始的,但是在linq中,可以从xelement开始

         //  一般创建方式
            public void GeneratorXml()
            {
                XElement xele = new XElement("customers",
                    new XElement("customer",
                          new XAttribute("id", "1"),
                          new XAttribute("city", "beijing")
                        )
                  
    
                    );
                Console.WriteLine(xele);
            }
    

    2,从数据库导出xml

    值得注意的是,这是两张表的联动,第一张customer表记录的是客户的一般信息,order表记录的是客户的订单情况,他们用customid作为主外键建立外键关系

     XElement xele = new XElement ("customers",  

                             from c in study.Customer.AsEnumerable()
                             select new XElement("customer",
                             new XAttribute("id",c.CustomerID),.......

    为什么可以这样写??

    对比上面一般创建xml的方法,我们可以发现,XElement xele=new XElement(param1,param2,......)这是一种用参数列表创建xml文件 ,还记得这样的形似吗?

    varchar result=from item in datalist select new(a=item.id,b=item,name); 

    foreach(var i in result){

    console.writeline(i); //这个会输出什么?? {a=4,b=hihi}  ,这就是var自己推断类型

    }

    我们先不妨将上面简化一下,改成只有一张表的

      XElement x = new XElement("customers",
                    from c in study.Customer
                    select new XElement("customer", c.Order)
                    );  这里只有一张表,而且只有两层(customers,customer)
    这里因为在new 后又xElement 也就是说这就匿名类的类型是确认的,是一个xelement,
    from c in study.Customer select new XElement("customer", c.Order) 改行的结果:<customer>c.order(确定的值)</customer>
    在类型确定的情况下,把上面结果也就是一个element替换上面表达式linq部分,就是简单的 XElement x = new XElement("customers",<customer......./>)
    同理,在两层表时也一样
    public void test()
            {
                studyEntities2 study = new studyEntities2();
    
                XElement xele = new XElement ("customers",
                 from c in study.Customer.AsEnumerable()
                 select new XElement("customer",
                     new XAttribute("id",c.CustomerID),
                     new XAttribute("city",c.City),
                     new XElement("orders",
                       // from d in study.Order.AsEnumerable()
    //where d.CustomerID==c.CustomerID 这两种方法都可以。因为在 customer表和order表以customId作为外键,from d in c.Order
    from d in c.Order select new XElement("order", new XAttribute("id",d.ID), new XAttribute("orderdata",d.OrderDate), d.ShipName ) ) ) ); string filePath = "../../xmlFromDataBase.xml"; xele.Save(filePath); //不存在会自己创建 XElement element = XElement.Load(filePath); Console.WriteLine(element); // Console.WriteLine(xele); }

      值得注意的是:上面从数据库导出xml还有很多地方值得我们去推敲:

     1.from c in study.Customer.AsEnumerable()

    其中的AsEnumerable()是干嘛的呢?

    书上解曰:    LINQ to Entities查询把Northwind数据上下文对象的Customers成员作为数据源,通过Customers、Orders和Order Details表生成包含了所有顾客订单的列表。但是,由于LINQ to Entities查询的延迟执行,我们使用Customer对象上的AsEnumerable()方法把中间结果转换为内存中的LINQ to Objects可枚举类型。最后,查询结果被投影到查询的select子句中,成为一组嵌套的LINQ to XML元素和特性。

    也就是说,linq to entities 是即查即用的,子查询不能利用父查询,通过AsEnumerable()将中间结果保存在内存中,方便子查询。如果除掉会报错

    2.   from d in study.Order.AsEnumerable()  where d.CustomerID==c.CustomerID 
          from d in c.Order

    这两种方法都可以。因为在 customer表和order表以customId作为外键。通过from d in c.Order  可以建立customer和order主外键的关系,通过他们,可以选择出所有customerId对应的order表中的数据

  • 相关阅读:
    TransactionScop事务机制的使用
    MVC无刷新上传图片并显示
    WebClient和WebRequest获取html代码
    Web.config配置详解
    分类和扩展有什么区别?可以分别用来做什么?分类有哪些局限性?分类的结构体里面有哪些成员?
    有序二维数组的查找
    生成Excel.xlsx文件 iOS
    charles Https抓包
    https 通信流程和Charles 抓包原理
    fastlane自动化打包ipa并发布到firim或者蒲公英
  • 原文地址:https://www.cnblogs.com/fjsnail/p/3228290.html
Copyright © 2020-2023  润新知