开发者

Using .Net XmlSerialize for strings with embedded <cr><lf> loses <cr> 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 af开发者_如何学运维fected 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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜