2010-10-15 224 views
1

我想根據嵌套元素的值在我的XML中選擇一個元素。LINQ to XML - 基於嵌套元素值獲取元素

這裏是XML的例子:

<Agents> 
    <Agent ID="xxx"> 
     <Login>xxx</Login> 
     <Password>xxxx</Password> 
     <Products> 
      <Product ID="zzz"> 
      </Product> 
     </Products> 
    </Agent> 
</Agents> 

這是我在LINQ查詢第一次嘗試:

var DetailsOfUserAccount = 
    from agent in policySpecificationXml 
     .Descendants("Agent") 
     .FirstOrDefault(p => (string)p.Attribute("ID") == productId) 
     .Descendants() 
    select new 

感謝。

+0

你可以在你的問題更清楚了嗎?你期待的結果是什麼?如果您只是給我們第一次嘗試而沒有指明您嘗試的是什麼問題,我們該如何幫助您? – 2010-10-15 11:18:18

+0

對不起mastoj。基本上,如果我有很多代理節點,我想選擇包含帶產品ID的產品節點的代理,只使用產品ID進行搜索。 – FloatLeft 2010-10-16 07:49:14

回答

2

尚不完全清楚,但聽起來好像要像...

var detailsOfUserAccount = policySpecificationXml 
    .Descendants("Agent") 
    .Where(agent => agent.Descandants("Product") 
         .Any(product => (string)product.Attribute("ID") 
              == productId)) 
    .FirstOrDefault(); 
+0

謝謝Timwi,那太好了。 – FloatLeft 2010-10-16 07:46:24