Skip to content

Instantly share code, notes, and snippets.

@lallousx86
Created January 14, 2016 19:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lallousx86/bee1969512e7107c32c3 to your computer and use it in GitHub Desktop.
Save lallousx86/bee1969512e7107c32c3 to your computer and use it in GitHub Desktop.
C# XML serialize/deserialize
public static class XmlExtensions
{
static public string GetAttrValue(
this XmlNode node,
string AttrName)
{
try
{
return node.Attributes[AttrName].Value;
}
catch (Exception)
{
return null;
}
}
public static bool SerializeToXmlFile(
this object obj,
string FileName,
out string ExMessage)
{
try
{
using (TextWriter writer = new StreamWriter(FileName))
{
XmlSerializer ser = new XmlSerializer(obj.GetType());
ser.Serialize(writer, obj);
}
ExMessage = null;
return true;
}
catch (Exception ex)
{
ExMessage = ex.ToString();
Debug.WriteLine(
string.Format("SerializeToXmlFile failed to serialize {0} of the type {1}.\n" +
"Exception: {2}",
FileName,
obj.GetType().Name,
ExMessage));
return false;
}
}
public static bool SerializeToXmlFile(
this object obj,
string FileName)
{
string ExMessage;
return obj.SerializeToXmlFile(FileName, out ExMessage);
}
public static T DeserializeFromXmlFile<T>(
string FileName,
out string ExMessage) where T : class
{
try
{
using (TextReader reader = new StreamReader(FileName))
{
ExMessage = null;
XmlSerializer ser = new XmlSerializer(typeof(T));
return ser.Deserialize(reader) as T;
}
}
catch (Exception ex)
{
ExMessage = ex.ToString();
Debug.WriteLine(
string.Format("DeserializeFromFile failed to deserialize {0} of the type {1}.\n" +
"Exception: {2}",
FileName,
typeof(T).Name,
ExMessage));
return default(T);
}
}
public static T DeserializeFromXmlFile<T>(string FileName) where T : class
{
string ExMessage;
return DeserializeFromXmlFile<T>(FileName, out ExMessage);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment