2011-03-11 71 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") 

注:您将不得不在标签内添加一些元素以便能够选择它们