public class MainClass
{
public object Data { get; set; }
}
public class ChildClass1
{
//some properties
}
public class ChildClass2
{
//some properties
}
where Child Classes can be assigned to Data property of the MainClass and if you construct XmlSerializer object like this
new XmlSerializer(typeof(MainClass));
Then both serialization and deserialization will fail throwing an error saying that it has no knowledge of ChildClass1 or ChildClass2 classes. To resolve this error you need to provide XmlSerializer with additional class types which serializer may meet on its way when parsing XML string. Here is how to do that:
new XmlSerializer(typeof(MainClass), new Type[] { typeof(ChildClass1), typeof(ChildClass2) });
Here is the set of functions I use to serialize / deserialize my objects:
public static string SerializeToString(object aObject)
{
return SerializeToString(aObject, null);
}
public static string SerializeToString(object aObject, Type[] extraTypes)
{
XmlSerializer aSerializer;
if (extraTypes == null)
aSerializer = new XmlSerializer(aObject.GetType());
else
aSerializer = new XmlSerializer(aObject.GetType(), extraTypes);
MemoryStream aMemoryStream = new MemoryStream();
StreamReader aStreamReader = new StreamReader(aMemoryStream);
XmlWriterSettings aXMLWriterSettings = new XmlWriterSettings();
aXMLWriterSettings.Encoding = new UTF8Encoding(false);
aXMLWriterSettings.ConformanceLevel = ConformanceLevel.Document;
XmlWriter aXMLWriter = XmlWriter.Create(aMemoryStream, aXMLWriterSettings);
aSerializer.Serialize(aXMLWriter, aObject);
aXMLWriter.Flush();
aXMLWriter.Close();
aMemoryStream.Position = 0;
return aStreamReader.ReadToEnd();
}
public static object DeserializeFromString(string aMessage, System.Type aType)
{
return DeserializeFromString(aMessage, aType, null);
}
public static object DeserializeFromString(string aMessage, System.Type aType, Type[] extraTypes)
{
XmlSerializer aXMLSerializer;
if (extraTypes == null)
aXMLSerializer = new XmlSerializer(aType);
else
aXMLSerializer = new XmlSerializer(aType, extraTypes);
System.IO.StringReader aStringReader = new StringReader(aMessage);
return aXMLSerializer.Deserialize(aStringReader);
}
-= Oleg =-
No comments:
Post a Comment