Skip to content

Instantly share code, notes, and snippets.

@ArseniySavin
Last active May 15, 2020 16:52
Show Gist options
  • Select an option

  • Save ArseniySavin/df5e3da4aa9526477291f1c2bcd52c4a to your computer and use it in GitHub Desktop.

Select an option

Save ArseniySavin/df5e3da4aa9526477291f1c2bcd52c4a to your computer and use it in GitHub Desktop.
Model serializer
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