2011-03-11 69 views
0

我想根據該元素的子元素的屬性選擇元素。通過後代元素的屬性過濾XElements

原始的XML:

<Root> 
     <Element1 id="1"> 
     <element2>XXXX</element2> 
     <element2>XXXX</element2> 
     <element2>XXXX</element2> 
     <Filter attr1="1" attr2="0" attr3="0" attr4="1" attr5="0"></Filter> 
     </Element1> 
     <Element1 id="2"> 
     <element2>XXXX</element2> 
     <element2>XXXX</element2> 
     <element2>XXXX</element2> 
     <Filter attr1="1" attr2="0" attr3="0" attr4="1" attr5="0"></Filter> 
     </Element1> 
     <Element1 id="3"> 
     <element2>XXXX</element2> 
     <element2>XXXX</element2> 
     <element2>XXXX</element2> 
     <Filter attr1="1" attr2="0" attr3="0" attr4="1" attr5="0"></Filter> 
     </Element1> 
    </Root> 

這是我迄今所做的:

Dim xmlElement = (From rec In RecipeXmlDocument.Descendants("RECEPT") _ 
Where (rec.Descendants("Filter")[email protected] = Ing.Poultry.ToString() _ 
        Or rec.Descendants("Filter")[email protected] = "1" _ 
        Or rec.Descendants("Filter")[email protected] = "0" _ 
        And (rec.Descendants("Filter")[email protected] = "1" _ 
         Or rec.Descendants("Filter")[email protected] = "0" _ 
         Or rec.Descendants("Filter")[email protected] = "1" 

這引發以下錯誤:「類型 'System.Linq.SystemCore_EnumerableDebugViewEmptyException' 引發的異常「。

代碼試圖做的是選擇所有Element1s,其中element1的過濾元素與語句的where子句相匹配。

我對linq相當陌生,我不確定我做錯了什麼。

+1

請發佈完整的示例,以便我們重現此問題。考慮到發佈的示例不包含任何名爲「RECEPT」的元素,在發佈的示例文檔中執行'RecipeXmlDocument.Descendants(「RECEPT」)'似乎很奇怪。爲了解釋錯誤,我們需要查看足夠的信息來重現它。 – 2011-03-11 11:32:47

+0

對不起,在我發佈的示例Xml中,「RECEPT」元素是「Element1」。 – Martinffx 2011-03-14 07:14:28

回答

0

你想從xml中選擇什麼?您的linq語句中缺少select語句。 添加選擇你的LINQ語句結尾,例如選擇(無論從標籤)

此外,你導航「在」您要查找的元素,即

From rec In RecipeXmlDocument.Descendants("RECEPT") 

From rec In RecipeXmlDocument.Descendants 

下面是一個修改語句,你需要連接你的SELECT語句其中

Dim xmlElement = From rec In RecipeXmlDocument.Descendants Where rec...<Filter>[email protected] = Ing.Poultry.ToString Or rec...<Filter>[email protected] = "1" Or rec...<Filter>[email protected] = "0" And (rec...<Filter>[email protected] = "1" Or rec...<Filter>[email protected] = "0" Or rec...<Filter>[email protected] = "1") 

注:您將不得不在標籤內添加一些元素以便能夠選擇它們