I’m stumped yet again by XDocument. I’m trying to extract the value of the temperature element (12 in this example) when the class attribute has a value=”high” (and “low”)
A subset of my XML:
<forecastGroup>
<forecast>
<temperatures>
<textSummary>Low plus 2. High 12.</textSummary>
<temperature unitType="metric" units="C" class="high">12</temperature>
<temperature unitType="metric" units="C" class="low">2</temperature>
</temperatures>
</forecast>
...etc.
<forecast>
<temperature unitType="metric" units="C" class="high">15</temperature>
<temperature unitType="metric" units="C" class="low">3</temperature>
</forecast>
<forecastGroup>
Code so far:
XDocument loaded = XDocument.Parse(strInputXML);
foreach (var forecast in loaded.Descendants("forecastGroup").Elements("forecast"))
{
//existing code doing stuff here using the XDocument loaded
High = "this is where I'm lost";
}
I’ve seemingly tried every combinations of trying to select Elements, Attributes, and Descendants”, but I’m at a loss.
To extract the high inside your loop, you could use the line
Of course, you could use Linq-to-XML to simply project the entire XML tree into an appropriate object graph without explicitly taking it apart in a loop, but you should be able to progress your way towards that. It may end up looking something like