Reputation: 3625
I am querying XML using LINQ TO XML. I want to query records based on some conditional check here is my XML below: XML will have multiple Orders each order will be in I want to select order which has param node attribute store value is not null and if exists should be 1 and also order with carton information...
<orders>
<order>
<criteria>
<param name="location">123</param>
<param name="name">Chicago</param>
<param name="Store">1</param>
<param name="Account Number">1212121212</param>
</criteria>
<items>
<item> </item>
<item> </item>
</items>
<cartons>
<carton>
<size> </size>
<weight></weight>
</carton>
</cartons>
</order>
<Order>
</Order>
</orders>
I am able to do till this:
var result = from item in doc.Descendants("order")
where item.Element("criteria").Element("param").Attribute("name").Value.Contains("store") == true
&& item.Element("cartons") != null
select item;"
Above works fine if my store (param) attribute is first in the filter node but if I move the store(param) to other position than first it does not filter it
Upvotes: 0
Views: 3567
Reputation: 1503290
The problem is that you're only looking at one param
element - always the first one, because that's what the Element
does.
You want to match if any of the parameters is a "Store" element with a value of 1, so you want to use the Any
method and use Elements
to find all the parameters:
var query = from item in doc.Descendants("order")
where item.Element("criteria").Elements("param")
.Any(p => p.Attribute("name").Value == "Store" &&
(int) p == 1)
&& item.Element("cartons") != null
select item;
The query expression isn't really helping you here - I'd use:
var query = doc.Descendants("order")
.Where(item => item.Element("criteria").Elements("param")
.Any(p => p.Attribute("name").Value == "Store" &&
(int) p == 1)
&& item.Element("cartons") != null);
Upvotes: 5