Question Deserialize Xml with carriage returns

groadsvb

Well-known member
Joined
Nov 13, 2006
Messages
75
Programming Experience
Beginner
I have an application that will be deserializing xml which will contain text that has carriage returns. When I deserialize the xml and put it in my sql database there is no indication that the carriage returns are still there. I sent an email asking the other party what format can I get the carriage returns in and I was told what ever format I needed. Well I don't know. If I am using microsoft xmlserialization and I want to keep the carriager returns what do I need to do? thanks.
 
This reproduces the problem:
Class X
    Public content As String = "test" & vbNewLine & "test"
End Class

Dim obj As New X

Using target As New IO.StringWriter
    Dim ser As New Xml.Serialization.XmlSerializer(obj.GetType)
    ser.Serialize(target, New X)
    Using source As New IO.StringReader(target.ToString)
        obj = CType(ser.Deserialize(source), X)
        Debug.WriteLine(obj.content.Contains(vbNewLine)) 'False
    End Using
End Using

One note about this code, the deserialized content here still has a vbLf where the serialized content had a vbCrLf (vbNewline), so this is something you can work with also.

This solves it:
Using target As New IO.StringWriter
    Dim ser As New Xml.Serialization.XmlSerializer(obj.GetType)
    Dim settings As New Xml.XmlWriterSettings
    settings.NewLineHandling = NewLineHandling.Entitize
    Using writer = Xml.XmlTextWriter.Create(target, settings)
        ser.Serialize(writer, New X)
    End Using
    Using source As New IO.StringReader(target.ToString)
        obj = CType(ser.Deserialize(source), X)
        Debug.WriteLine(obj.content.Contains(vbNewLine)) 'True
    End Using
End Using
 
Back
Top