Search code examples
c#xmlwindows-phone

Can't get attributes of an xml element properly


I'm trying to get the attributes value of this yahoo weather XML element:

<yweather:wind chill="24" direction="340" speed="28.97" /> 

like this:

XDocument XResult = XDocument.Parse(e.Result);

XElement location = XResult.Elements(XName.Get("wind", "yweather")).FirstOrDefault();

XAttribute city = location.Attributes(XName.Get("chill")).FirstOrDefault();
XAttribute direction = location.Attributes(XName.Get("direction")).FirstOrDefault();
XAttribute speed = location.Attributes(XName.Get("speed")).FirstOrDefault();

but it tells me object not set to an instance. How can I fix this?


Solution

  • You should use the namespace uri instead of namespace name, for example :

    XElement location = XResult.Elements(XName.Get("wind", "http://xml.weather.yahoo.com/ns/rss/1.0"))
                               .FirstOrDefault();
    

    if the element is direct child of root node, this simplified one should work as well :

    XElement location = XResult.Element(XName.Get("wind", "http://xml.weather.yahoo.com/ns/rss/1.0"));
    

    otherwise you need to use Descendants() instead of Elements() :

    XElement location = XResult.Descendants(XName.Get("wind", "http://xml.weather.yahoo.com/ns/rss/1.0"))
                               .FirstOrDefault();