Removing deserializing empty element as null

I am deserializing some XML from an old application to an object in my current application. Old XML often contains empty elements ( <SomeElement />

), which are currently deserialized as empty strings ( ""

).

I agree that this is the most appropriate behavior, but it is a minor annoyance; I would prefer them to be deserialized as Nothing

or ideally ignored - the effect will be the same.

Is there a way to ignore these elements? Or can I deserialize them like Nothing

?

CONCLUSION: Both of the listed solutions have their merits ...

Aaron's solution would be perfect if I only had one property of the problem - that's one fix for one problem.

If there are multiple problems with multiple properties, svick's solution is preferred. The ISerializable implementation involves creating a constructor and GetObjectData method with specific handling for each property.

My solution: Since my problem is only related to some legacy XML files (which have died out over time), and since String.IsNullOrEmpty allows me to ignore the problem, I decided not to do anything. I don't need the additional overhead of maintaining the ISerializable interface if not necessary, but in many cases it would be a good solution, so this is my chosen answer.

+3


source to share


2 answers


I haven't found any other simple simple way to do this. But you can always implement IXmlSerializable

and handle serialization and deserialization 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

      

+2


source


As far as I know, no, you cannot deserialize a Nothing element if the element exists in XML, because the deserializer recognizes that the element exists and contains an empty string.

<SomeElement/>

      

matches:



<SomeElement></SomeElement>

      

If you need this behavior, perhaps create a property for your variable that 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

      

+1


source







All Articles