Linq强制转换Xelement错误:无法将类型为'System.Xml.Linq.XElement'的对象强制转换为'System.IConvertible'

Hai*_*ock 3 c# xml linq casting linq-to-xml

我正在尝试解析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"))
};  
Run Code Online (Sandbox Code Playgroud)

我收到错误:

无法将类型为"System.Xml.Linq.XElement"的对象强制转换为"System.IConvertible".

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

Ser*_*kiy 6

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

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")
           };    
Run Code Online (Sandbox Code Playgroud)

Linq to Xml支持显式转换运算符.

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

Lat = Convert.ToDouble(node.Element("lat").Value)
Run Code Online (Sandbox Code Playgroud)

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