views:

194

answers:

1

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
A: 

Take a look at http://stackoverflow.com/questions/1115459/xml-deserialization-standardising-line-endings-how-to-stop-it-net. Does that soluton match what you're trying to do?

Justin Grant