[英]Linq cast conversion Xelement error: Unable to cast object of type 'System.Xml.Linq.XElement' to type 'System.IConvertible'
I'm attempting to parse an XML document as follows: 我正在尝试解析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"))
};
I'm getting the error: 我收到错误:
Unable to cast object of type 'System.Xml.Linq.XElement' to type 'System.IConvertible'.
无法将类型为“System.Xml.Linq.XElement”的对象强制转换为“System.IConvertible”。
When I check the value of node I'm getting all the elements from the locations children properly, but it doesn't want to break it up for me. 当我检查节点的值时,我正确地从子位置获取所有元素,但它不想为我分解它。 I've checked errors similar to this but can't figure out what I am doing wrong.
我检查过类似的错误,但无法弄清楚我做错了什么。 Any suggestions?
有什么建议?
You don't need to convert elements or attributes to double. 您不需要将元素或属性转换为double。 Simply cast them to 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")
};
Linq to Xml supports explicit cast operators . Linq to Xml支持显式转换运算符 。
And yes, XElement
does not implement IConvertable
interface, thus you can't pass it to Convert.ToDouble(object value)
method. 是的,
XElement
没有实现IConvertable
接口,因此你无法将它传递给Convert.ToDouble(object value)
方法。 Your code will work with passing node value to Convert.ToDouble(string value)
method. 您的代码将使用将节点值传递给
Convert.ToDouble(string value)
方法。 Like this: 像这样:
Lat = Convert.ToDouble(node.Element("lat").Value)
But again, better simply cast node to double
type. 但同样,更好的是简单地将节点转换为
double
类型。 Or to double?
还是
double?
(nullable) if it is possible that you can have missing attribute or element in your xml. (可空)如果您的xml中可能缺少属性或元素。 Accessing
Value
property in that case will raise NullReferenceException
. 在这种情况下访问
Value
属性将引发NullReferenceException
。
Are you not simply missing the .Value
property 你是不是简单地错过了
.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)
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.