I am new to .NET and I am having some trouble implementing queries in LINQ to XML.
I have a XML file in a strange format:
<calendar>
<event>
<amount>1200</amount>
<age>40</age>
<country>FR</country>
<amount>255</amount>
<age>16</age>
<country>UK</country>
<amount>10524</amount>
<age>18</age>
<country>FR</country>
<amount>45</amount>
<age>12</age>
<country>CH</country>
<event>
<event>
<amount>1540</amount>
<age>25</age>
<country>UK</country>
<amount>255</amount>
<age>31</age>
<country>CH</country>
<amount>4310</amount>
<age>33</age>
<country>FR</country>
<amount>45</amount>
<age>17</age>
<country>FR</country>
<event>
</calendar>
From this file I want to compute the sum of every <amount> element value, where <age> is greater than ’20’ and <country> is either ‘FR’ or ‘CH’.
This operation is independent of the tag <event> (all <amount> elements that check the above conditions should be summed, whether they’re under the same or different <event> elements).
My problem is that I have no element tag that groups <amount>, <age> and <country> together… (I can’t change the XML format, I’m consuming it from a Web Service I can’t access).
If I had an hypothetical <transfer> tag grouping these triples together, I think the code would be simply:
XElement root = XElement.Load("calendar.xml");
IEnumerable<XElement> sum =
from trf in root.Elements("events").Elements("transfers")
where (decimal) trf.Element("age") > 20 &&
((string) trf.Element("Country") == "FR" ||
(string) trf.Element("Country") == "cH")
select trf.Element("Amount").Sum();
Should I programatically group these elements? Thanks in advance!
Try this:
I have tested the code. You also have to make sure that amount element must be the first element in the group.