Share via


Reading int and byte values from XElement

The XElement class has a very nice capability that is not very well known - the ability to by typecasted to different types to read data from within.

For example, if I have an XElement instance element, I can write (int)element, and the content of the element will be read, parsed as an int and returned.

If you look at the list of conversions available here, you'll notice that not all possible numeric types are supported. For example, bytes aren't on the list. You might also wonder as to how the nullable types behave - are null'ed values ever returned, and if so when?

I put together a little sample to show a few interesting things:

  • How do I read the value into a byte? 
  • What happens if there is no value?
  • What happens if the value is too large to fit into a byte?

Here's the code, with the output of running it.

string

[] tests = new string[] { "<Root />", "<Root></Root>", "<Root>10</Root>", "<Root>1000</Root>" };
bool[] checkedMathValues = new bool[] { true, false };
foreach (bool checkedMath in checkedMathValues)
{
  foreach (string test in tests)
{
    Console.WriteLine("Converting " + ((checkedMath) ? "(checked)" : "") + ": " + test);
    try
    {
      if (checkedMath)
{
        Console.WriteLine(" " + checked((byte?)(int?)XElement.Parse(test)));
}
      else
      {
        Console.WriteLine(" " + (byte?)(int?)XElement.Parse(test));
}
}
    catch (FormatException e) { Console.WriteLine(" FormatException: " + e.Message); }
    catch (OverflowException e) { Console.WriteLine(" OverflowException: " + e.Message); }
}
}

This is the output produce by the code:

Converting (checked): <Root />
  FormatException: Input string was not in a correct format.
Converting (checked): <Root></Root>
  FormatException: Input string was not in a correct format.
Converting (checked): <Root>10</Root>
  10
Converting (checked): <Root>1000</Root>
  OverflowException: Arithmetic operation resulted in an overflow.
Converting : <Root />
  FormatException: Input string was not in a correct format.
Converting : <Root></Root>
  FormatException: Input string was not in a correct format.
Converting : <Root>10</Root>
  10
Converting : <Root>1000</Root>
  232

Enjoy!

Comments

  • Anonymous
    March 11, 2009
    Many thanks for this information.

  • Anonymous
    March 23, 2009
    More importantly, the cast operators for nullable types and strings works even if the element is null: XElement element = null; int? intValue = (int?)element; // Contains null This is particularly useful when querying a document with optional elements, as you don't have to check whether the element exists first.