Last active
May 15, 2020 16:52
-
-
Save ArseniySavin/df5e3da4aa9526477291f1c2bcd52c4a to your computer and use it in GitHub Desktop.
Model serializer
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
| public static T Deserialize<T>(string xmlPath) | |
| { | |
| try | |
| { | |
| using (FileStream fileReader = new FileStream(xmlPath, FileMode.Open, FileAccess.Read)) | |
| { | |
| T result = (T)new XmlSerializer(typeof(T)).Deserialize(fileReader); | |
| fileReader.Close(); | |
| return result; | |
| } | |
| } | |
| catch (Exception e) | |
| { | |
| throw e; | |
| } | |
| } | |
| public static string SerializeToXml<T>(this T model) | |
| { | |
| try | |
| { | |
| using (MemoryStream stream = new MemoryStream()) { | |
| new XmlSerializer(typeof(T)).Serialize(stream, model); | |
| return Encoding.UTF8.GetString(stream.ToArray()); | |
| } | |
| } | |
| catch (Exception e) | |
| { | |
| throw e; | |
| } | |
| } | |
| } | |
| // ignore xmlns="" | |
| XmlRootAttribute xRoot = new XmlRootAttribute(); | |
| xRoot.ElementName = "RootElementName"; | |
| xRoot.IsNullable = true; | |
| XmlSerializer objSer = new XmlSerializer(typeof(Result), xRoot); | |
| FileStream objF = new FileStream("C:\\a.xml", FileMode.Open); | |
| Result varResult = (Result)serializer.Deserialize(objF); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment