Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing empty element as null

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.

like image 970
CJM Avatar asked Feb 27 '26 01:02

CJM


2 Answers

I didn't find any other clear simple way to do this. But you can always implement IXmlSerializable and handle the serialization and deserialization by yourself:

Public Sub ReadXml(ByVal reader As XmlReader) Implements IXmlSerializable.ReadXml

    reader.ReadStartElement()
    If (reader.Name = "SomeElement") Then
        Dim someElementValue = reader.ReadElementString()

        If someElementValue <> String.Empty Then
            SomeElement = someElementValue
        End If
    End If
    reader.ReadEndElement()

End Sub
like image 54
svick Avatar answered Mar 01 '26 17:03

svick


As far as I'm aware, no, you cannot deserialize the element to Nothing if the element exists in the XML, because the deserializer recognises that the element exists and contains an empty string.

<SomeElement/>

is the same as:

<SomeElement></SomeElement>

If you need this behaviour, perhaps create a property for your variable which returns Nothing if it finds an empty string.

Public ReadOnly Property SomeElement() As String
    Get
        If SomeElementValue = "" Then
            Return Nothing
        Else
            Return SomeElementValue
        End If
    End Get
End Property
like image 24
aaroncatlin Avatar answered Mar 01 '26 17:03

aaroncatlin