I’m trying to select elements based on the attributes of sub a element of that element.
Original Xml:
<Root>
<Element1 id="1">
<element2>XXXX</element2>
<element3>XXXX</element3>
<element4>XXXX</element4>
<Filter attr1="1" attr2="0" attr3="0" attr4="1" attr5="0"></Filter>
</Element1>
<Element1 id="2">
<element2>XXXX</element2>
<element3>XXXX</element3>
<element4>XXXX</element4>
<Filter attr1="1" attr2="0" attr3="1" attr4="1" attr5="0"></Filter>
</Element1>
<Element1 id="3">
<element2>XXXX</element2>
<element3>XXXX</element3>
<element4>XXXX</element4>
<Filter attr1="1" attr2="1" attr3="0" attr4="1" attr5="0"></Filter>
</Element1>
</Root>
This is what I’ve done so far:
Dim xmlElement = (From rec In RecipeXmlDocument.Descendants("Element1") _
Where (rec.Descendants("Filter").@attr1= "1" _
Or rec.Descendants("Filter").@attr2 = "0" _
Or rec.Descendants("Filter").@attr3 = "0" _
And (rec.Descendants("Filter").@attr4 = "1" _
Or rec.Descendants("Filter").@attr5 = "0" _
This throws the following error: “Exception of type ‘System.Linq.SystemCore_EnumerableDebugViewEmptyException’ was thrown.”
What the code is trying to do is to select all the Element1s where the filter element of that element1 matches the where clause of the statement.
I’m fairly new to linq and i’m not exactly sure what I’m doing wrong.
This is a case where it’s likely that XPath will produce the right result with less work than it would take to do with LINQ. You can formulate an XPath query like:
(I added parentheses around the tests conjoined with
orbecause I suspect that’s what you want, but I could be wrong.) That will find allElement1elements that have aFilterchild element whose attributes pass the predicate described.Then you can just iterate over those elements by using
XDocument.XPathSelectElements():