Nombreux sont les projets où on a des données à sérialiser au format XML.
Voici deux méthodes créées pour un projet qui pourraient être utilisées dans une class Helper XML.
Les deux méthodes sont génériques et permettent la validation du schéma XSD
public static T GetDataFromXML<T>(string dataSourcePath, XmlSchemaSet xmlSchemaSet) {
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlReaderSettings readerSettings = new XmlReaderSettings();
if (xmlSchemaSet != null) {
readerSettings.Schemas = xmlSchemaSet;
readerSettings.ValidationType = ValidationType.Schema;
}
using (XmlReader reader = XmlReader.Create(dataSourcePath, readerSettings)) {
return (T) serializer.Deserialize(reader);
}
}
public static void SetXML<T>(string dataDestinationPath,T t, XmlSerializerNamespaces namespaces)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlWriterSettings writterSettings = new XmlWriterSettings();
writterSettings.ConformanceLevel = ConformanceLevel.Auto;
writterSettings.Indent = true;
if (namespaces == null)
namespaces = new XmlSerializerNamespaces();
namespaces.Add( "xsi", http://www.w3.org/2001/XMLSchema-instance);
using (XmlWriter writer = XmlWriter.Create(dataDestinationPath, writterSettings)) { serializer.Serialize(writer,t, namespaces); } }