Kilgore_Trout_Redux
Executive Member
- Joined
- Sep 20, 2006
- Messages
- 7,498
- Reaction score
- 347
A better way of serializing/deserializing XML (Assuming you don't want to use loose coupling and interfaces/DI to make it easier to switch between JSON or something down the line... (I should probably cover my arse considering how critical I've been
))
Also partially bashed out quickly on my phone. (Why the hell am I being so damn defensive.
Code:
public static string XmlSerializer<T>(T item)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, item);
return writer.ToString();
}
}
public static T XmlDeserializer<T>(string item)
{
using (StringReader stringReader = new StringReader(item))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
return (T)xmlSerializer.Deserialize(stringReader);
}
}
...
Foo foo = new Foo();
//hydrate Foo, whatever the hell it is.
string stringVersionOfFoo = XmlSerializer(foo);
Foo foo2 = XmlDeserializer<Foo>(stringVersionOfFoo);
Also partially bashed out quickly on my phone. (Why the hell am I being so damn defensive.