Tuesday, October 21, 2008

LINQ to XML How to add Namespace when parsing the XML

LINQ TO XML XML Namespace

If you look at my pervious BLOG , were i am using weather webservice to get weather information for given Zipcode. this Webmethod call returns XML Data. when i parse Weather service response XML i am always getting the null values for the XML element i was querying.

Finally i found out that to access these elements we need to add XML Namespace to Xname. here is the code which shows how i did that.

private void ParsexWeatherXml(string exml)
{
XNamespace ns = "http://www.webservicex.net"; // Weather Service Namespace
XDocument weatherData = XDocument.Parse(exml );
var query = from data in weatherData.Descendants(ns + "WeatherData")

select new WeatherData
{
day = (string)data.Element(ns + "Day").Value ,
urlImage =(string) data.Element(ns+"WeatherImage").Value,
maxTemp = (string)data.Element(ns + "MaxTemperatureF").Value,
minTemp = (string)data.Element(ns + "MinTemperatureF").Value
};
datag.ItemsSource = query;

}


Thanks
BNK
SeenivasaRagavan.

No comments: