Pulling XML element use C#; loop fails -


i trying hourly weather forecast wunderground. can weather data 1st hour, loop fails pull data of next few hours. wondering how revise code. url wunderground http://api.wunderground.com/api/b6fa7ac0ff6723ec/geolookup/hourly/q/mi/ann_arbor.xml

i new c#. if have better ways this, appreciate help. in advance!

private static void parse2(string input_xml2)         {             string hour = "";             string tempen = "";             string tempme = "";              xmldocument xml = new xmldocument();             xml.load(input_xml2);              xmlnodelist xnlist = xml.selectnodes("/response/hourly_forecast/forecast");              foreach (xmlnode xnfore in xnlist)             {                   xmlnode xnhour = xml.selectsinglenode("/response/hourly_forecast/forecast/fcttime");                 xmlnode xntemp = xml.selectsinglenode("/response/hourly_forecast/forecast/temp");                  hour = xnhour["hour"].innertext;                 tempen = xntemp["english"].innertext;                 tempme = xntemp["metric"].innertext;                  console.writeline("********************");                 console.writeline("hour:              " + hour);                 console.writeline("temperature:       " + tempen + " f" + " (" + tempme + " c)");             }         } 

i'd inclined ditch ancient xmldocument api , use linq xml:

const string url = "http://api.wunderground.com/api/b6fa7ac0ff6723ec/geolookup/hourly/q/mi/ann_arbor.xml";  var doc = xdocument.load(url);  var forecasts = doc.descendants("hourly_forecast").elements("forecast");  foreach (var forecast in forecasts) {     var hour = (string)forecast.elements("fcttime").elements("hour").single();     var english = (int)forecast.elements("temp").elements("english").single();     var metric = (int)forecast.elements("temp").elements("metric").single();      console.writeline("********************");     console.writeline("hour:\t\t{0}", hour);     console.writeline("temperature:\t{0}f ({1}c)", english, metric); } 

a working example here: https://dotnetfiddle.net/q1czse

if have xml string already, can parse rather load it:

var doc = xdocument.parse(xml); 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -