S
steinmr
I have a class with an enum field which is serialized. For whatever
reason, the enum value that was serialized, no longer exists in the
enum. When I deserialize, I get an InvalidOperationException. Is there
any way of ignoring this error in the xml document, set the enum to
the default value, and continue deserialization?
Sample program below, throws an exception on the last line, but not if
the line before it is removed...
public class Program
{
public class MyClass
{
public MyEnum MyEnumField = MyEnum.MyEnumValue;
}
public enum MyEnum
{
MyEnumValue
}
static void Main(string[] args)
{
MyClass myClass = new MyClass();
System.Xml.Serialization.XmlSerializer xmlSerializer
= new System.Xml.Serialization.XmlSerializer(typeof(MyClass));
System.IO.StringWriter stringStream = new System.IO.StringWriter();
xmlSerializer.Serialize(new System.Xml.XmlTextWriter(stringStream),
myClass);
string serializedString = stringStream.ToString();
// Deserialize after modification
serializedString = serializedString.Replace("MyEnumValue",
"AnInvalidEnumValue");
MyClass deserializedClass
= (MyClass)xmlSerializer.Deserialize(
new System.Xml.XmlTextReader(new
System.IO.StringReader(serializedString)));
}
}
reason, the enum value that was serialized, no longer exists in the
enum. When I deserialize, I get an InvalidOperationException. Is there
any way of ignoring this error in the xml document, set the enum to
the default value, and continue deserialization?
Sample program below, throws an exception on the last line, but not if
the line before it is removed...
public class Program
{
public class MyClass
{
public MyEnum MyEnumField = MyEnum.MyEnumValue;
}
public enum MyEnum
{
MyEnumValue
}
static void Main(string[] args)
{
MyClass myClass = new MyClass();
System.Xml.Serialization.XmlSerializer xmlSerializer
= new System.Xml.Serialization.XmlSerializer(typeof(MyClass));
System.IO.StringWriter stringStream = new System.IO.StringWriter();
xmlSerializer.Serialize(new System.Xml.XmlTextWriter(stringStream),
myClass);
string serializedString = stringStream.ToString();
// Deserialize after modification
serializedString = serializedString.Replace("MyEnumValue",
"AnInvalidEnumValue");
MyClass deserializedClass
= (MyClass)xmlSerializer.Deserialize(
new System.Xml.XmlTextReader(new
System.IO.StringReader(serializedString)));
}
}