zoukankan      html  css  js  c++  java
  • c# in deep 之LINQ读取xml(2)

        假如有以下xml文件

    <?xml version="1.0" encoding="utf-8" ?>
    <Date>
      <Products>
        <Product Name="West Size Story" Price="9.99" SupplierID="1"/>
        <Product Name="Assassins" Price="14.99" SupplierID="2"/>
        <Product Name="Frogs" Price="13.99" SupplierID="1"/>
        <Product Name="Sweeney Todd" Price="10.99" SupplierID="3"/>
      </Products>
      <Suppliers>
        <Supplier Name="Solely Sondheim" SupplierID="1"/>
        <Supplier Name="CD-by-CD-bySondheim" SupplierID="2"/>
        <Supplier Name="Barbershop CDs" SupplierID="3"/>
      </Suppliers>
    </Date>

      首先引用Xml.Linq命名空间,然后用以下方法进行读取

    XDocument doc = XDocument.Load("XMLFile1.xml");
                var filtered = from p in doc.Descendants("Product")
                               join s in doc.Descendants("Supplier")
                               on (int)p.Attribute("SupplierID")
                               equals (int)s.Attribute("SupplierID")
                               orderby (string)s.Attribute("Name"),
                                       (string)p.Attribute("Name")
                               select new
                               {
                                   SupplierName = (string)s.Attribute("Name"),
                                   ProductName = (string)p.Attribute("Name")
                               };
                foreach (var v in filtered)
                {
                    Console.WriteLine("SupplierName={0}---ProductName={1}",v.SupplierName,v.ProductName);
                }
                Console.ReadKey();

    即可得到结果.

    浮躁的人容易问:我到底该学什么;----别问,学就对了; 浮躁的人容易问:JS有钱途吗;----建议你去抢银行; 浮躁的人容易说:我要中文版!我英文不行!----不行?学呀! 浮躁的人分两种:只观望而不学的人;只学而不坚持的人; 浮躁的人永远不是一个高手。
  • 相关阅读:
    今天英语有何新收获?
    今天了解了解了外包这一行业
    今天英语有何新收获?
    sicp 练习1.7
    今天英语有何新收获
    今天英语有何新收获?
    反射(初尝)
    初学正则表达式
    sicp 练习1.8 【有点疑惑】
    [tip]Windows filename MAX_PATH limitation
  • 原文地址:https://www.cnblogs.com/xuekai-to-sharp/p/3336406.html
Copyright © 2011-2022 走看看