using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml.Serialization;
static string filepath = "TestSerilize.xml";
private static object oSchema;
private static XmlReaderSettings oXmlReaderSettings;
public static void Main(string[] args)
MyObject oMyobject = new MyObject();
oMyobject.MyObjectType = "MyCustomType";
List<Items> olistItems = new List<Items>();
Items oItems = new Items();
oItems.value = "testvalue";
oMyobject.Items = olistItems;
Saveobjecttofile(oMyobject, filepath);
dynamic objDeserialized = null;
objDeserialized = GetObjFormfileWithoutValidation(filepath, oMyobject.GetType());
objDeserialized = GetObjFormfileWithValidation(filepath, oMyobject.GetType());
private static dynamic GetObjFormfileWithValidation(string filepath, Type type)
XmlReaderSettings oXmlReaderSettings = new XmlReaderSettings();
oXmlReaderSettings.ValidationType = ValidationType.Schema;
dynamic oSchema = GetSchemaFromType(type);
oXmlReaderSettings.Schemas.Add(oSchema);
XmlReader oXmlReader = null;
oXmlReader = XmlReader.Create(filepath, oXmlReaderSettings);
oXmlReader = XmlReader.Create(filepath);
XmlSerializer oXmlSerializer = new XmlSerializer(type);
obj = oXmlSerializer.Deserialize(oXmlReader);
private static XmlSchema GetSchemaFromType(Type type)
var oSoapReflectionImporter = new SoapReflectionImporter();
var oXmlTypeMapping = oSoapReflectionImporter.ImportTypeMapping(type);
var oXmlSchemas = new XmlSchemas();
var oXmlSchema = new XmlSchema();
oXmlSchemas.Add(oXmlSchema);
var oXMLSchemaExporter = new XmlSchemaExporter(oXmlSchemas);
oXMLSchemaExporter.ExportTypeMapping(oXmlTypeMapping);
private static dynamic GetObjFormfileWithoutValidation(string filepath, Type type)
XmlReader oXmlReader = null;
oXmlReader = XmlReader.Create(filepath);
XmlSerializer oXmlSerializer = new XmlSerializer(type);
obj = oXmlSerializer.Deserialize(oXmlReader);
private static void Saveobjecttofile(object objectToSave, string filepath)
System.Xml.Serialization.XmlSerializer oXmlSerializer = new System.Xml.Serialization.XmlSerializer(objectToSave.GetType());
using (System.Xml.XmlTextWriter oXmlTextWriter = new System.Xml.XmlTextWriter(filepath, System.Text.Encoding.UTF8))
oXmlTextWriter.Indentation = 2;
oXmlTextWriter.Formatting = System.Xml.Formatting.Indented;
oXmlSerializer.Serialize(oXmlTextWriter, objectToSave);
public string key { get; set; }
public string value { get; set; }
[Serializable, XmlRoot("MyObject")]
[XmlElement("MyObjectType", IsNullable = true)]
public string MyObjectType { get; set; }
public List<Items> Items;
public string this[string key]
return null != Items.Find(x => x.key == key) ? Items.Find(x => x.key == key).value : null;
if (Items == null) Items = new List<Items>();
if (null != Items.Find(x => x.key == key))
Items.Find(x => x.key == key).value = value;
Items.Add(new Items { key = key, value = value });