Reputation: 65
I have some XML like the following
<USTrades>
<USTrade>
<BalanceAmount>1000</BalanceAmount>
<Narratives>
<Narrative code="1" description="Code 1"/>
<Narrative code="2" description="Code 2"/>
</Narratives>
</USTrade>
<USTrade>
<BalanceAmount>2000</BalanceAmount>
<Narratives>
<Narrative code="3" description="Code 3"/>
</Narratives>
</USTrade>
</USTrades>
I would like to select the sum of the balances where the Narrative code is not equal to 3, so my result with this XML would be 1000. The code below looks like it is selecting the correct Narratives, but i dont know how to then select the correct parent based off of the child condition
var trades = document.Descendants("USTrades").Descendants("Narratives").Descendants("Narrative").Where(n => (string)n.Attribute("code") != "3");
Upvotes: 1
Views: 77
Reputation: 1438
This query yields the wanted result:
var r = x.Elements("USTrades")
.Elements("USTrade")
.Where(e => e.Element("Narratives")
.Elements("Narrative")
.All(ee => ee.Attribute("code").Value != "3"))
.Select(e => (int)e.Element("BalanceAmount"))
.Sum();
I have tested it with the following XML:
<USTrades>
<USTrade>
<BalanceAmount>1000</BalanceAmount>
<Narratives>
<Narrative code="1" description="Code 1"/>
<Narrative code="2" description="Code 2"/>
</Narratives>
</USTrade>
<USTrade>
<BalanceAmount>2000</BalanceAmount>
<Narratives>
<Narrative code="3" description="Code 3"/>
</Narratives>
</USTrade>
<USTrade>
<BalanceAmount>3000</BalanceAmount>
<Narratives>
<Narrative code="4" description="Code 4"/>
</Narratives>
</USTrade>
</USTrades>
Here r
is 4000
, in your original XML it is 1000
.
Upvotes: 1