我试图获取此yahoo weather XML元素的属性值:
<yweather:wind chill="24" direction="340" speed="28.97" />
像这样:
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();
但它告诉我没有设置实例的对象。我该如何解决这个问题?
答案 0 :(得分:0)
您应该使用命名空间uri而不是命名空间名称,例如:
XElement location = XResult.Elements(XName.Get("wind", "http://xml.weather.yahoo.com/ns/rss/1.0"))
.FirstOrDefault();
如果元素是根节点的直接子节点,那么这个简化元素也应该起作用:
XElement location = XResult.Element(XName.Get("wind", "http://xml.weather.yahoo.com/ns/rss/1.0"));
否则您需要使用Descendants()
代替Elements()
:
XElement location = XResult.Descendants(XName.Get("wind", "http://xml.weather.yahoo.com/ns/rss/1.0"))
.FirstOrDefault();
答案 1 :(得分:0)
就像这样
XDocument XResult = XDocument.Parse(e.Result);
XElement location = XResult.Descendants(XName.Get("wind", "http://xml.weather.yahoo.com/ns/rss/1.0")).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();