Linq cast convertion Xelement error

I am trying to parse an XML document like this:

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 am getting the error:

Cannot overlay object of type 'System.Xml.Linq.XElement' on type 'System.IConvertible'.

When I check the node value, I am getting all the elements from the child locations correctly, but it doesn't want to split it for me. I have checked errors like this but cannot figure out what I am doing wrong. Any suggestions?

+3


source to share


2 answers


You don't need to convert elements or attributes to double. Just add 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 translation operators .



And yes, it XElement

does not implement an interface IConvertable

, so you cannot pass it to a method Convert.ToDouble(object value)

. Your code will work by passing the node value to the method Convert.ToDouble(string value)

. Like this:

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

      

But again, it's better to just put node in double

. Or up to double?

(nullable) if it is possible that you may be missing an attribute or element in your xml. Accessing the property Value

in this case will raise the value NullReferenceException

.

+6


source


You don't just lose 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)
                  };  

      

+1


source







All Articles