Skip to content

Instantly share code, notes, and snippets.

@zmilojko
Last active May 11, 2020 03:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmilojko/9343394 to your computer and use it in GitHub Desktop.
Save zmilojko/9343394 to your computer and use it in GitHub Desktop.
C# XML (de)serialization made simple. I am sick of C# approach to use 12 lines of code where one would suffice. These two functions will (de)serialize string <=> object and with nice format two.
string Serialize(object o)
{
XmlWriterSettings Settings = new XmlWriterSettings()
{
Indent = true,
IndentChars = " ",
NewLineHandling = NewLineHandling.None,
NewLineChars = "\n",
};
var sb = new StringBuilder();
var writer = XmlWriter.Create(sb, Settings);
new XmlSerializer(o.GetType()).Serialize(writer, o);
writer.Close();
return sb.ToString();
}
T Deserialize<T>(string input_string)
{
using (TextReader reader = new StringReader(input_string))
{
return (T)new XmlSerializer(typeof(T)).Deserialize(reader);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment