繁体   English   中英

无法正确获取xml元素的属性

[英]Can't get attributes of an xml element properly

我正在尝试获取此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();

但它告诉我对象未设置为实例。 我怎样才能解决这个问题?

您应该使用名称空间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();

就像这样

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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM