![](/img/trans.png)
[英]Error: Unable to cast object of type 'WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String]' to type 'System.IConvertible'
[英]Linq cast conversion Xelement error: Unable to cast object of type 'System.Xml.Linq.XElement' to type 'System.IConvertible'
我正在嘗試解析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”。
當我檢查節點的值時,我正確地從子位置獲取所有元素,但它不想為我分解它。 我檢查過類似的錯誤,但無法弄清楚我做錯了什么。 有什么建議?
您不需要將元素或屬性轉換為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支持顯式轉換運算符 。
是的, XElement
沒有實現IConvertable
接口,因此你無法將它傳遞給Convert.ToDouble(object value)
方法。 您的代碼將使用將節點值傳遞給Convert.ToDouble(string value)
方法。 像這樣:
Lat = Convert.ToDouble(node.Element("lat").Value)
但同樣,更好的是簡單地將節點轉換為double
類型。 還是double?
(可空)如果您的xml中可能缺少屬性或元素。 在這種情況下訪問Value
屬性將引發NullReferenceException
。
你是不是簡單地錯過了.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.