We use xml serialization / deserialization extensively in our project to pass data between multiple application. We have a common xsd that we generate c# classes from then use XmlSerializer to go from xml to objects and back.
The problem we are having is when one app is updated to add new enum values but the other app is not updated yet. Now the app that is not updated tries to deserialize the xml and fails because it doesn't know about the new enum.
If we have app1 and app2, things are working correctly in the field, then app2 is update with a new enum value in the xsd and updated to the client in the field. Suddenly app1 breaks because it doesn't know about the enum, app1 might not even use that enum field, has not effect on app1, but it still breaks.
Are there any known ways around this. Basically what i want to do is define what do do when an enum is not found, use a default value or if the enum as a nullible type and set it to null.
Both XmlSerializer and DataContractSerializer throw exceptions is this situation.
I've looked at the custom xml serialization project YAXLib (http://www.codeproject.com/KB/XML/yaxlib.aspx) this also throws an exception but there is source code and can be changed. This project use different property attributes and would require quite a bit of change but is probably doable.
Any other suggestions.
Yes, you can tell the XmlSerializer to ignore namespaces during de-serialization. Note this is the kind of thing I meant. You are not telling the XmlSerializer to ignore namespaces - you are giving it XML that has no namespaces.
Since XmlSerializer is one of the few thread safe classes in the framework you really only need a single instance of each serializer even in a multithreaded application.
The XmlSerializer creates C# (. cs) files and compiles them into . dll files in the directory named by the TEMP environment variable; serialization occurs with those DLLs. These serialization assemblies can be generated in advance and signed by using the SGen.exe tool.
With the XmlSerializer you can take advantage of working with strongly typed classes and still have the flexibility of XML. Using fields or properties of type XmlElement, XmlAttribute or XmlNode in your strongly typed classes, you can read parts of the XML document directly into XML objects.
Unfortunately there's no way to control how enum values are deserialized... As a workaround, you could serialize the enum values as string :
[XmlIgnore]
public MyEnum MyProperty { get; set; }
[XmlElement("MyProperty")]
public string MyPropertyAsString
{
get
{
return EnumToString(MyProperty);
}
set
{
MyProperty = StringToEnum<MyEnum>(value);
}
}
public T StringToEnum<T>(string stringValue)
{
// Manually convert the string to enum, ignoring unknown values
}
public string EnumToString<T>(T enumValue)
{
// Convert the enum to a string
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With