Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 659
Hairlock Avatar asked Jan 14 '23 11:01

Hairlock


2 Answers

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.

like image 54
Sergey Berezovskiy Avatar answered Jan 31 '23 08:01

Sergey Berezovskiy


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)
                  };  
like image 45
NinjaNye Avatar answered Jan 31 '23 07:01

NinjaNye