2010-10-16 97 views
0

我想我正在推動LINQ to XML能力的界限,但我想選擇一組包含與值匹配的值的元素包含在另一個元素節點中。LINQ to XML - 基於其他元素中存在的值選擇元素

在下面我想選擇包含也被包含在AvailableOptions」元素特定產品ID值只有「選項」的元素的XML

類似下面的僞代碼:

選擇全部選項,其中選項名稱是(選擇AvailableOptions其中的ProductID = 「XXX」)

<Agents> 
<Agent ID="1"> 
    <Login>111</Login> 
    <Password>pass</Password> 
    <Products> 
     <Product ID="xxx"> 
      <AvaiableOptions>aaa,bbb</AvaiableOptions> 
     </Product> 
    </Products> 
    <Products> 
     <Product ID="yyy"> 
      <AvaiableOptions>bbb,ccc</AvaiableOptions> 
     </Product> 
    </Products> 
    <Products> 
     <Product ID="zzz"> 
      <AvaiableOptions>aaa,ccc</AvaiableOptions> 
     </Product> 
    </Products> 
    <Options> 
     <Option> 
      <Name>aaa</Name> 
      <Value>10</Value> 
     </Option> 
     <Option> 
      <Name>bbb</Name> 
      <Value>20</Value> 
     </Option> 
     <Option> 
      <Name>ccc</Name> 
      <Value>30</Value> 
     </Option> 
    </Options> 
</Agent> 

回答

0

這是我的嘗試,雖然有點冗長。希望能幫助到你。

var query = from agent in agents.Descendants("Agent") 
      from products in agent.Descendants("Products") 
      from product in products.Descendants("Product") 
      where product.Attribute("ID").Value == "xxx" 
      from options in agent.Descendants("Options") 
      from option in options.Descendants("Option") 
      where product.Element("AvaiableOptions").Value.Contains(option.Element("Name").Value) 
      select option; 
+0

是的,這就是它。謝謝。我只是不能讓我的頭腦如何構建這樣的查詢。 – FloatLeft 2010-10-16 17:49:35