Converting from String to <T>

I would suggest instead of trying to parse XML yourself, you try to create classes that would deserialize from the XML into the classes. I would strongly recommend following bendewey's answer.

But if you cannot do this, there is hope. You can use Convert.ChangeType.

public static T GetValue<T>(String value)
{
  return (T)Convert.ChangeType(value, typeof(T));
}

And use like so

GetValue<int>("12"); // = 12
GetValue<DateTime>("12/12/98");

If you decide to go the route of serialization to POCO (Plain old CLR Object), then there are few tools that can help you generate your objects.

  • You can use xsd.exe to generate a .cs file based on your XML Definition
  • There is a new feature in the WCF REST Starter Kit Preview 2, called Paste as Html. This feature is really cool and lets you take a block of HTML thats in your clipboard, then when you paste it into a cs file it automatically converts the xml to the CLR object for serialization.

You can start with something roughly like this:

TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
if (converter != null)
{
   return (T)converter.ConvertFrom(value);
}

If you have to parse attributes that are special types, like colors or culture strings or whatnot, you will of course have to build special cases into the above. But this will handle most of your primitive types.

Tags:

C#

Xml

Generics