加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Linq强制转换Xelement错误:无法将类型为’System.Xml.Lin

发布时间:2020-12-16 01:52:35 所属栏目:百科 来源:网络整理
导读:我正在尝试解析 XML文档,如下所示: var locs = from node in doc.Descendants("locations") select new{ ID = (double)Convert.ToDouble(node.Attribute("id")),File = (string)node.Element("file"),Location = (string)node.Element("location"),Postcode
我正在尝试解析 XML文档,如下所示:

var locs = from node in doc.Descendants("locations")                              
select new
{
    ID = (double)Convert.ToDouble(node.Attribute("id")),File = (string)node.Element("file"),Location = (string)node.Element("location"),Postcode = (string)node.Element("postCode"),Lat = (double)Convert.ToDouble(node.Element("lat")),Lng = (double)Convert.ToDouble(node.Element("lng"))
};

我收到错误:

Unable to cast object of type ‘System.Xml.Linq.XElement’ to type
‘System.IConvertible’.

当我检查节点的值时,我正确地从子位置获取所有元素,但它不想为我分解它.我检查过类似的错误,但无法弄清楚我做错了什么.有什么建议?

解决方法

您不需要将元素或属性转换为double.简单地将它们加倍:

var locs = from node in doc.Descendants("locations")
           select new
           {
               ID = (double)node.Attribute("id"),Lat = (double)node.Element("lat"),Lng = (double)node.Element("lng")
           };

Linq to Xml支持显式cast operators.

是的,XElement没有实现IConvertable接口,因此你无法将它传递给Convert.ToDouble(对象值)方法.您的代码将使用将节点值传递给Convert.ToDouble(字符串值)方法.像这样:

Lat = Convert.ToDouble(node.Element("lat").Value)

但同样,更好的是简单地将节点转换为double类型.还是加倍? (可空)如果您的xml中可能缺少属性或元素.在这种情况下访问Value属性将引发NullReferenceException.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读