zoukankan      html  css  js  c++  java
  • C# linq to xml 简单示例

    data.xml

     1 <?xml version="1.0" encoding="utf-8" ?>
     2 <Data>
     3   <Products>
     4     <Product Name="West Side Story" Price="9.99" SupplierID="1" />
     5     <Product Name="Assassins" Price="14.99" SupplierID="2" />  
     6     <Product Name="Frogs" Price="13.99" SupplierID="1" />
     7     <Product Name="Sweeney Todd" Price="10.99" SupplierID="3" />
     8   </Products>
     9 
    10   <Suppliers>
    11     <Supplier Name="Solely Sondheim" SupplierID="1" />
    12     <Supplier Name="CD-by-CD-by-Sondheim" SupplierID="2" />
    13     <Supplier Name="Barbershop CDs" SupplierID="3" />
    14   </Suppliers>
    15 </Data>

    通过 linq to xml ,查找价格超过10的产品,并打印供应商名称与产品名称;

     1             XDocument doc = XDocument.Load("data.xml");
     2             var filtered = from p in doc.Descendants("Product")
     3                            join s in doc.Descendants("Supplier")
     4                            on (int)p.Attribute("SupplierID")
     5                            equals (int)s.Attribute("SupplierID")
     6                            where (decimal)p.Attribute("Price") > 10
     7                            select new
     8                            {
     9                                ProductName = (string)p.Attribute("Name"),
    10                                SupplierName = (string)s.Attribute("Name")
    11                            };
    12 
    13             foreach (var v in filtered)
    14             {
    15                 Console.WriteLine("SupplierName={0} , ProductName={1}", v.SupplierName, v.ProductName);
    16             }

    输出

    SupplierName=CD-by-CD-by-Sondheim , ProductName=Assassins
    SupplierName=Solely Sondheim , ProductName=Frogs
    SupplierName=Barbershop CDs , ProductName=Sweeney Todd

     

    参考资料

    1、深入理解C#(第2版);

  • 相关阅读:
    洛谷 P4861 按钮
    《情人》
    bzoj1019: [SHOI2008]汉诺塔(dp)
    hdu5698瞬间移动(组合数,逆元)
    poj Code(组合数)
    组合数 牛顿二项式定理 杨辉三角
    8.22 NOIP 模拟题
    codevs2495 水叮当的舞步(IDA*)
    codevs 2541 幂运算(迭代加深搜索)
    较复杂搜索,剪枝
  • 原文地址:https://www.cnblogs.com/fanful/p/7954933.html
Copyright © 2011-2022 走看看