Using .Net XmlSerialize for strings with embedded loses when deserializing

The following (abysmal) code demonstrates how standard serialize/de-serialize in VB loses the CR when on de-serialize. This can be overcome by applying 'XmlAttribute(DataType:="string")' to Description. Why does it do this? I would like to fix this without applying a 'LF' -> 'CR''LF' in every affected class. This is fixing a bug in existing XML files generated without the XmlAttribute!

  Imports System.Xml.Serialization
  Imports System.Xml
  Imports System.IO

  Public Class Form1

    Public Class MyObject
      Public Description As String
    End Class

    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

      Dim x As New MyObject
      x.Description = "Hello" + vbCrLf + "World"
      Dim serializer As New XmlSerializer(GetType(MyObject))
      Dim writer As StreamWriter = New StreamWriter("c:\temp\test.xml")
      serializer.Serialize(writer, x)

      writer.Close()

      For i As Integer = 0 To x.Description.ToCharArray.Length - 1
        Debug.Print(Asc(x.Description.ToCharArray(i, 1)))
      Next

      Debug.Print("**********************")

      Dim reader As New StreamReader("c:\temp\test.xml")

      Dim newObj As MyObject = CType(serializer.Deserialize(reader), MyObject)

      For i As Integer = 0 To newObj.Description.ToCharArray.Length - 1
        Debug.Print(Asc(newObj.Description.ToCharArray(i, 1)))
      Next

    End Sub
  End Class
13.10.2009 19:49:26
Test that code with multiple CRLF in a row.
John Saunders 16.10.2009 04:51:29
1 ОТВЕТ

Take a look at XML deserialization 'standardising' line endings, how to stop it? (.NET). Does that soluton match what you're trying to do?

1
23.05.2017 12:30:28