Skip to content

Instantly share code, notes, and snippets.

@gcapnias
Created March 8, 2019 16:14
Show Gist options
  • Select an option

  • Save gcapnias/c3dc4721457b6501f7bb2293ce7c8aa1 to your computer and use it in GitHub Desktop.

Select an option

Save gcapnias/c3dc4721457b6501f7bb2293ce7c8aa1 to your computer and use it in GitHub Desktop.
Serialize/Deserialize object to XML
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="buffer"></param>
/// <returns></returns>
public static T FromXML<T>(string buffer)
{
if (string.IsNullOrEmpty(buffer))
{
throw new ArgumentNullException(nameof(buffer));
}
T r = default(T);
using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(buffer)))
{
XmlReaderSettings settings = new XmlReaderSettings();
using (XmlReader reader = XmlReader.Create(memoryStream, settings))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
if (xmlSerializer.CanDeserialize(reader))
{
r = (T)xmlSerializer.Deserialize(reader);
}
}
}
return r;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <returns></returns>
public static string ToXml<T>(this T model)
{
string returnValue = null;
if (model != null)
{
StringBuilder sb = new StringBuilder();
using (XmlWriter xmlWriter = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true, }))
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(xmlWriter, model, ns);
}
returnValue = sb.ToString();
sb = null;
}
return returnValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment