Soy fan de los métodos de extensión, por lo tanto, yo uso esto siempre:
using System.IO;
using System.Xml.Serialization;
public static class SerializationExtensionMethods
{
/// <summary>
/// Serializes the object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="toSerialize">To serialize.</param>
/// <returns></returns>
public static string SerializeObjectToXml<T>(this T toSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
StringWriter textWriter = new StringWriter();
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
/// <summary>
/// Serializes the object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="toSerialize">To serialize.</param>
/// <param name="path">The path.</param>
public static void SerializeObjectToFile<T>(this T toSerialize, string path)
{
string xml = SerializeObjectToXml<T>(toSerialize);
using (StreamWriter sw = new StreamWriter(path, false))
{
sw.Write(xml);
}
}
/// <summary>
/// Deserializes the specified XML.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml">The XML.</param>
/// <returns></returns>
public static T DeserializeFromXml<T>(this T original, string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
TextReader textReader = new StringReader(xml);
return (T)serializer.Deserialize(textReader);
}
/// <summary>
/// Deserializes the specified object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="original">The original.</param>
/// <param name="path">The path.</param>
/// <returns></returns>
public static T DeserializeFromFile<T>(this T original, string path)
{
string xml = string.Empty;
using (StreamReader sr = new StreamReader(path))
{
xml = sr.ReadToEnd();
}
return DeserializeFromXml<T>(original, xml);
}
}
uso para serializar:
YourClassType obj = new YourClassType();
o
List<YourClassType> obj = new List<YourClassType>();
string xml = obj.SerializeObjectToXml();
o
obj.SerializeObjectToFile("PathToYourFile"); // It will save a file with your classes serialized (works with everything with the [Serializable] attribute).
Uso deserializar:
YourClassType obj = new YourClassType().DeserializeFromXml("XML string here");
List<YourClassType> obj = new List<YourClassType>().DeserializeFromFile("XML string here");
o
YourClassType obj = new YourClassType().DeserializeFromFile("PathToYourFile");
y lo tienes funcionando :)
Prefiero los métodos de extensión porque le permite tener su código muy limpio, esto funciona con todo tipo de tipo de objeto que tenga, en la medida en que implemente el atributo [Serializable]
.
Si es necesario especificar cómo se va a serializar (como nodos o atributos), se puede añadir el atributo en cada una de sus propiedades, tales como:
[XmlElement("NameOfTheElementYouWant")]
[XmlAttribute("NameOfTheAttributeYouWant")]
[XmlText]
Espero que esto ayude a alguien en el futuro.
Alejandro
-1 por no implementar bloques "usar" y por no usar genéricos. –
usando (XmlSerializer deserializer = new XmlSerializer (_type)) no funciona. XmlSerializer no implementó IDisposable. El correcto debería ser como la respuesta de John, poniendo XmlSerializer fuera del bloque de uso. –
Vaya, olvidé por un momento que XmlSerializer no implementó IDisposable, corregido :) – amazedsaint