62 lines
2.1 KiB
C#
62 lines
2.1 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Xml.Serialization;
|
|
|
|
namespace IOB_UT_NEXT.Services
|
|
{
|
|
/// <summary>
|
|
/// Gestisce le operazioni di serializzazione e deserializzazione in formato XML.
|
|
/// </summary>
|
|
public static class XmlDataSerializer
|
|
{
|
|
/// <summary>
|
|
/// Serializza un oggetto in una stringa XML.
|
|
/// </summary>
|
|
/// <typeparam name="T">Tipo dell'oggetto.</typeparam>
|
|
/// <param name="obj">L'oggetto da serializzare.</param>
|
|
/// <returns>Stringa XML o null se l'oggetto è null.</returns>
|
|
public static string Serialize<T>(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);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Deserializza una stringa XML in un oggetto del tipo specificato.
|
|
/// </summary>
|
|
/// <typeparam name="T">Tipo dell'oggetto.</typeparam>
|
|
/// <param name="xmlString">La stringa XML.</param>
|
|
/// <returns>L'oggetto deserializzato o default se la stringa è nulla/vuota.</returns>
|
|
public static T Deserialize<T>(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);
|
|
}
|
|
}
|
|
}
|
|
}
|