Reputation: 251
i need to pull data out of an xml file based on certain field values. the xml file is set up like this
<main>
<report>
<version>1.0</version>
<ID>1234</ID>
<field>
<acel>80</acel>
<decel>50</decel>
<left>20</left>
<right>10</right>
<category>1-10</category>
</field>
<field>
<acel>30</acel>
<decel>54</decel>
<left>12</left>
<right>13</right>
<category>10-20</category>
</field>
<field>
<acel>34</acel>
<decel>210</decel>
<left>27</left>
<right>9</right>
<category>20-30</category>
</field>
</report>
<report>
....
</report>
</main>
I currently have the following:
var query = doc.Descendants("report")
.Select(raw => new
{
version = (string)raw.Element("version"),
tcid = (string)raw.Element("id"),
forces = raw.Element("field").Elements("acel").Select(acel => (int)acel).ToList()
});
I need to search the file for reports that match specific ID's and specific versions, and then get the accsociated fields acel, decel, left, right etc.
ex I need to find a report for ID 1234 and version 1.0, and have all the field values 80, 50 etc. Any help is great. I have code that returns ID and version already but I'm having trouble getting all the values of field based on version and ID.
Thanks.
Upvotes: 1
Views: 513
Reputation: 273844
You start by inserting a .Where()
:
var query = doc
.Descendants("report")
.Where(r => r.Element("version").Value == "1.0"
&& r.Element("ID").Value == "1234")
.Select(raw => new
{
version = (string)raw.Element("version"),
tcid = (string)raw.Element("id"),
forces = raw.Element("field").Elements("acel")
.Select(acel => (int)acel).ToList()
});
Upvotes: 1
Reputation: 31484
To give you a hint:
var xDoc = XDocument.Parse(xml);
var fields = xDoc
.Descendants("report")
.Where(r => (int)r.Element("ID") == 1234)
.Elements("field")
.Select(f => new
{
Acel = f.Element("acel").Value,
Decel = f.Element("decel").Value,
}
);
We first fetch report
nodes and filter those to the ones matching ID
of 1234
- that leaves us with first one from your example. Next, we query all the field
nodes within this report, and extract new objects basing on field values. Looks simple awesome? It really is!
Upvotes: 0