I’m deserializing some XML from an old application into an object in my current application. The old XML often has empty elements (<SomeElement />) which are currently deserialized as empty strings ("").
I agree that this is the most appropriate behaviour, but it is a minor irritant; I’d rather they were deserialized as Nothing or ideally ignored – the effect would be the same.
Is there a means of ignoring these elements? Or can I have them deserialized as Nothing?
CONCLUSION:
Both solutions listed have their merits…
Aaron’s solution would be ideal if I had just had one problem property – it’s a single fix, for a single problem.
Where there are multiple properties that are problematic, svick’s solution is preferred. Implementing ISerializable involves creating a constructor and a GetObjectData method with specific handling for each property.
My decision: since my problem only involves some legacy XML files (which will die out over time), and since String.IsNullOrEmpty enables me to ignore the problem, I’ve decided to do nothing. I don’t want the additional overhead of maintaining the ISerializable interface if not necessary – but in many cases, this would be good solution, so it’s my selected answer.
I didn’t find any other clear simple way to do this. But you can always implement
IXmlSerializableand handle the serialization and deserialization by yourself: