data.xml
<?xml version="1.0" encoding="utf-8" ?>
<Data>
<Products>
<Product Name="West Side 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-by-Sondheim" SupplierID="2" />
<Supplier Name="Barbershop CDs" SupplierID="3" />
</Suppliers>
</Data>
通过 linq to xml ,查找价格超过10的产品,并打印供应商名称与产品名称;
XDocument doc = XDocument.Load("data.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")
where (decimal)p.Attribute("Price") >
select new
{
ProductName = (string)p.Attribute("Name"),
SupplierName = (string)s.Attribute("Name")
}; foreach (var v in filtered)
{
Console.WriteLine("SupplierName={0} , ProductName={1}", v.SupplierName, v.ProductName);
}
输出
SupplierName=CD-by-CD-by-Sondheim , ProductName=Assassins
SupplierName=Solely Sondheim , ProductName=Frogs
SupplierName=Barbershop CDs , ProductName=Sweeney Todd
参考资料
1、深入理解C#(第2版);