【问题标题】:Linq cast conversion Xelement error: Unable to cast object of type 'System.Xml.Linq.XElement' to type 'System.IConvertible'Linq 转换 Xelement 错误:无法将“System.Xml.Linq.XElement”类型的对象转换为“System.IConvertible”类型
【发布时间】:2013-01-19 21:00:55
【问题描述】:

我正在尝试按如下方式解析 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"))
};  

我收到了错误:

无法将“System.Xml.Linq.XElement”类型的对象转换为类型 'System.IConvertible'。

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

【问题讨论】:

    标签: c# xml linq casting linq-to-xml


    【解决方案1】:

    您不需要将元素或属性转换为双精度。只需将它们加倍:

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

    Linq to Xml 支持显式cast operators

    是的,XElement 没有实现IConvertable 接口,因此你不能将它传递给Convert.ToDouble(object value) 方法。您的代码将使用将节点值传递给 Convert.ToDouble(string value) 方法。像这样:

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

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

    【讨论】:

    • 使用演员表,这就是它的用途。
    • +1 - 我不知道显式转换运算符...每天学习新东西
    【解决方案2】:

    你不只是缺少.Value 属性

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

    【讨论】:

    • 奇怪,我之前尝试过但没有成功,这一定是我的错误。感谢您的回复。
    • 只要每个元素都在那里,它就可以工作,否则 OP 会在尝试获取 Value 属性时获得空引用异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多