Sérialiser un objet en XML

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);  } }

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Add comment


(Will show your Gravatar icon)  

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

January 6. 2009 01:23