using System;
using System.IO;
using System.Xml.Serialization;
namespace IOB_UT_NEXT.Services.Data
{
///
/// Gestisce le operazioni di serializzazione e deserializzazione in formato XML.
///
public static class XmlDataSerializer
{
///
/// Serializza un oggetto in una stringa XML.
///
/// Tipo dell'oggetto.
/// L'oggetto da serializzare.
/// Stringa XML o null se l'oggetto è null.
public static string Serialize(T obj)
{
if (obj == null) return null;
try
{
using (var stringWriter = new StringWriter())
{
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(stringWriter, obj);
return stringWriter.ToString();
}
}
catch (Exception ex)
{
throw new InvalidOperationException($"Errore durante la serializzazione XML per il tipo {typeof(T).Name}", ex);
}
}
///
/// Deserializza una stringa XML in un oggetto del tipo specificato.
///
/// Tipo dell'oggetto.
/// La stringa XML.
/// L'oggetto deserializzato o default se la stringa è nulla/vuota.
public static T Deserialize(string xmlString)
{
if (string.IsNullOrWhiteSpace(xmlString)) return default;
try
{
using (var stringReader = new StringReader(xmlString))
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stringReader);
}
}
catch (Exception ex)
{
throw new InvalidOperationException($"Errore durante la deserializzazione XML per il tipo {typeof(T).Name}", ex);
}
}
}
}