I’m using XML serialization to produce a file in a format specific to another application. One of the requirements is that all booleans be represented as 1 or 0. I’ve looked at some possibilities, including a struct to handle this easily and seamlessly. Currently I’m looking into another venue, which is to use an enum.
public enum BoolEnum
{
[XmlEnum("0")]
False = 0,
[XmlEnum("1")]
True = 1
}
So far, it works wonderfully, and it’s much cleaner. BUT (!) I’m also trying to make the deserialization easy, and I’d just like to be able to handle errors. If I produce an invalid tag:
<invalid>2</invalid>
to be deserialized as BoolEnum, I get an InvalidOperationException inside another InvalidOperationException. How can I catch that exception in an enum?
Addendum:
Deserialization function:
static void Deserialize<T>(out T result, string sourcePath) where T : class
{
FileStream fileStream = null;
try
{
fileStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
result = xmlSerializer.Deserialize(fileStream) as T;
}
finally
{
if (fileStream != null)
fileStream.Close();
}
}
Deserialized object:
public class Test
{
[XmlElement("someboolvalue")
public BoolEnum SomeBoolValue { get; set; }
}
You can use attributes to expose certain properties to Xml serialization, and hide other properties from it. Likewise you can expose certain properties to be visible via Intellisense, and hide others.
You can take advantage of this fact to use a different code-visible property type from the underlying serialization. This will allow you to use a
boolin code, and anintin serialization.If you choose this route, you can add custom serialization code to handle this case in the
intproperty’s getter/setter methods. E.g.