简体   繁体   中英

I Need Some Help Parsing XML with Linq

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 :

High = (int)x.Descendants("temperature")
            .Single(e => (string)e.Attribute("class") == "high")

This finds the only temperature descendant (if there are none or multiple, it will throw) having attribute class with value high , and then casts its value to an integer.

But it isn't entirely clear.

Can a forecast element have multiple temperatures elements? Can a temperatures element have multiple temperature elements that have class == "high" ? How do you want to deal with different unitTypes ?

To just get the elements out, you can do something like:

Highs = x.Descendants("temperature")
         .Where(e => (string)e.Attribute("class") == "high")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM