使用LINQ和where子句在xml中检索节点的数据

时间:2011-02-17 07:31:44

标签: linq-to-xml

我有以下XML:

<?xml version="1.0" encoding="utf-8" ?>   
<departments>  
  <department id="1">  
    <name>Mens Shirts</name>   
    <Products>  
      <Product>Mens Classic White</Product>   
      <Product>Mens Full whites</Product>   
    </Products>  
  </department>  
  <department id="2">  
    <name>Mens Trousers</name>   
    <Products>  
      <Product>Mens Formal Blacks</Product>   
      <Product>Mens Black Jeans</Product>   
    </Products>  
  </department>  
</departments>  

如何使用LINQ获取特定产品的部门名称?例如:find dept for product =“Mens Classic White”

1 个答案:

答案 0 :(得分:0)

您可以使用XDocument类从文件中获取信息。

var productName = "Mens Classic White";

XDocument doc= XDocument.Load(@"C:\xmlFile.xml");
var q = doc.Elements("departments")
    .Where(parent => parent.Elements(productName)
    .Any(child => child.Elements("department").Any()));