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();

即可得到结果.

 

 

 

 

 

 

 

 

 

 

 

posted @ 2013-09-24 10:31  蚂蚁拉车  阅读(266)  评论(0编辑  收藏  举报