I’m new to C# and XML and trying to develop a small weather plugin for MediaPortal. I’m trying to parse some XML using Linq in Visual C# 2010 Express and have hit a roadblock.
Here is a subset of the XML I am trying to parse:
<forecast>
<period textForecastName="Monday">Monday</period>
<textSummary>Sunny. Low 15. High 26.</textSummary>
<temperatures>
<textSummary>Low 15. High 26.</textSummary>
<temperature unitType="metric" units="C" class="high">26</temperature>
<temperature unitType="metric" units="C" class="low">15</temperature>
</temperatures>
</forecast>
Here is my working code so far:
XDocument loaded = XDocument.Parse(strInputXML);
var forecast = from x in loaded.Descendants("forecast")
select new
{
textSummary = x.Descendants("textSummary").First().Value,
Period = x.Descendants("period").First().Value,
Temperatures = x.Descendants("temperatures"),
Temperature = x.Descendants("temperature"),
//code to extract high e.g. High = x.Descendants(...class="high"???),
//code to extract low e.g. High = x.Descendants(...class="low"???)
};
My code works up to my placeholder comments, but I can’t figure out how to extract the high (26) and the low (15) from the XML using Linq. I could manually parse it from “Temperature”, but I’m hoping I can learn a bit more about XML structures.
Thanks for any help.
Doug
It looks like you want something like:
This finds the only
temperaturedescendant (if there are none or multiple, it will throw) having attributeclasswith valuehigh, and then casts its value to an integer.But it isn’t entirely clear.
Can a
forecastelement have multipletemperatureselements? Can atemperatureselement have multipletemperatureelements that haveclass == "high"? How do you want to deal with differentunitTypes?To just get the elements out, you can do something like: