开发者

Need help reading xml file in C#

I am making a program for Windows phone that will get weather data from a xml file and display it on screen. However, I keep getting null values and I am not sure what I am doing wrong.

Sample XML file: http://forecast.weather.gov/MapClick.php?lat=44.52160&lon=-87.98980&FcstType=dwml

Here is what I have:

try
{
    // get the stream containing the response from the async call
    streamResult = forecastState.AsyncResponse.GetResponseStream();

    // load the XML
    XElement xmlWeather = XElement.Load(streamResult);

    // find the source element
    XElement xmlCurrent = xmlWeather.Descendants("source").First();

    // get city and hei开发者_如何学运维ght
    xmlCurrent = xmlWeather.Descendants("location").First();
    mTempCityName = (string)(xmlCurrent.Element("city"));
    mTempHeight = (int)(xmlCurrent.Element("height"));

    //Find the forecast time
    xmlCurrent = xmlWeather.Descendants("time-layout").First();

    //store time of day in array
    mTimeOfDay = (string)(xmlCurrent.Attribute("period-name"));

    //Find the temperature
    xmlCurrent = xmlWeather.Descendants("temperature").First();
    mTemp = (int)(xmlCurrent.Element("value"));

    //now get the current weather conditions for each time period
    xmlCurrent = xmlWeather.Descendants("weather").First();
    mDescription = (string)(xmlCurrent.Attribute("weather-summary"));

    //now get icon links for weather
    xmlCurrent = xmlWeather.Descendants("conditions-icon").First();
    mIcon = (string)(xmlCurrent.Attribute("icon-link"));
}


Well:

  • time-layout doesn't have an attribute called period-name (it has subelements with that attribute)
  • temperature should be okay, I think
  • weather doesn't have a weather-summary attribute - it has subelements with that attribute
  • conditions-icon doesn't have an icons-link attribute, it has icons-link elements

In other words, for each bit you need to look at exactly what the XML contains, and then exactly what you're asking for, being careful to distinguish between elements and attributes.

Note that for the values you're casting to int (which don't need extra brackets around them, btw) you should be getting an exception in this case - you clearly can't be getting actual null values. Is it possible that an exception is being thrown and you're not noticing it? What's in your catch block?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜