How to parse XML attribute (string) to (int) during the LINQ query
Solution 1
Try this instead:
var layouts = from elem in layoutSummary.Descendants("Layout")
select new ComicLayout
{
Width = (int) elem.Attribute("Width"),
Height = (int) elem.Attribute("Height")
};
This uses the explicit conversion operator available from XAttribute
to int
, whose MSDN page you can find here.
Now obviously, this will throw a FormatException
if the conversion doesn't succeed. If that's not what you want, please indicate what you would like to happen. It is possible (if somewhat inconvenient) to use int.TryParse
here, but it would have to be done differently.
Solution 2
Try Convert.ToInt32
method
select new ComicLayout
{
Width = Convert.ToInt32( elem.Attribute("Width").Value),
Height = Convert.ToInt32(elem.Attribute("Height").Value)
};
Solution 3
select new ComicLayout
{
Width = elem.Attribute("Width") != null ?
Convert.ToInt32(elem.Attribute("Width").Value) :
-1,
Height = elem.Attribute("Height") != null ?
Convert.ToInt32(elem.Attribute("Height").Value) :
-1,
};
Solution 4
Width = int.Parse(elem.Attribute("Width").Value)
or
int w;
if (int.TryParse(elem.Attribute("Width").Value, out w)
Width = w;
Solution 5
You need Convert.ToInt32
I would also recommend adding checks to make sure it is an int so that you're not trying convert "three" to an integer. But I guess it depends on how much control you have over the xml coming back.
Comments
-
LukeP almost 2 years
I've got a class:
public class Layout { public int Width { get; set; } public int Height { get; set; } }
How do I read the XML attribute and assign it to int from the class above in the following LINQ query:
var layouts = from elem in layoutSummary.Descendants("Layout") select new Layout { // Width = elem.Attribute("Width").Value, // Invalid cast string to int) // Int32.TryParse((string)elem.Attribute("Height").Value, Height) // Doesn't assign Height value to Layout.Height };
-
LukeP over 12 yearsThat's exactly what I was after. The XML files are read-only and hard-embedded in the application. I can get away without handling failed conversion. Thank you!
-
LukeP over 12 yearsThanks. Much appreciated. Ani's solution seems simpler. Are there any benefits in using Convert.ToInt32 as opposed to plain casting?
-
LukeP over 12 yearsThe XML is going to be embedded into the application at build time and read-only
-
Adrian Ratnapala almost 11 yearsThe MSDN page says nothing about Culture (locale). I hope the converter uses is culture-invariant - i.e. a mate for
XmlConvert.ToString
; an ordinaryTryParse
would use the current culture unless you explicitly pass something else in.