对于嵌入了<cr> <lf>的字符串,使用.Net XmlSerialize在反序列化时丢失<cr> </cr> </lf> </cr>

时间:2009-10-13 19:49:26

标签: vb.net xml-serialization

以下(糟糕的)代码演示了在反序列化时VB中的标准序列化/反序列化如何丢失CR。这可以通过将'XmlAttribute(DataType:=“string”)'应用于Description来克服。为什么这样做?我想在没有应用'LF'的情况下解决这个问题 - &gt;每个受影响的班级都有'CR''LF'。这修正了在没有XmlAttribute的情况下生成的现有XML文件中的错误!

  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

1 个答案:

答案 0 :(得分:1)

看看XML deserialization 'standardising' line endings, how to stop it? (.NET)。这个解决方案是否符合您的目标?