Last active
May 11, 2020 03:05
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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