Hairlock
Hairlock

Reputation: 75

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:

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

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?

Upvotes: 4

Views: 6380

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

You don't need to convert elements or attributes to 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.

And yes, XElement does not implement IConvertable interface, thus you can't pass it to Convert.ToDouble(object value) method. Your code will work with passing node value to Convert.ToDouble(string value) method. Like this:

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

But again, better simply cast node to double type. Or to double? (nullable) if it is possible that you can have missing attribute or element in your xml. Accessing Value property in that case will raise NullReferenceException.

Upvotes: 8

NinjaNye
NinjaNye

Reputation: 7126

Are you not simply missing the .Value property

                  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)
                  };  

Upvotes: 2

Related Questions