2013-01-19 29 views
3

我試圖如下解析XML文檔:LINQ的投皈依的XElement錯誤

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'.

當我檢查節點i」的值m正確地從所在地的孩子處獲得所有要素,但它不想爲我分手。我檢查了類似這樣的錯誤,但無法弄清楚我做錯了什麼。有什麼建議麼?

回答

6

您不需要將元素或屬性轉換爲雙倍。簡單地把它們加倍:

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) 

但同樣,更好的只是投節點double類型。或者如果可能缺少xml中的屬性或元素,則返回double?(可爲空)。在這種情況下訪問Value財產將提高NullReferenceException

+1

使用鑄件,這就是它的存在了。 –

+1

+1 - 我不知道明確的演員......每天學點新東西 – NinjaNye

+1

哦,對,這很有道理。謝謝您的回答。 – Hairlock

1

你不只是缺少.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) 
        }; 
+0

奇怪的是,我之前試過,它沒有工作,它一定是我的錯誤。感謝您的迴應。 – Hairlock

+0

只要每個元素都在那裏,它就會工作,否則OP會得到空引用異常,試圖獲取Value屬性。 –