views:

459

answers:

2

Situation: When I deserialize XML that contains carriage returns, the characters appear as unprintable character "boxes" rather than as carriage returns.

Background: User input collected via a multi-line textbox contains carriage returns within the text. I am persisting this text data to XML using the .NET XML serializer (snippet below). When I later de-serialize the XML data and bind it back to the multi-line textbox, the carriage return characters render as unprintable "boxes".

I know Windows uses a carriage return + line feed to indicate an end-of-line. I think that the XML serializing may be altering the data (possibly stripping the carriage return?).

Question: Any ideas how can I get the deserialized carriage returns to render properly?

Thanks in advance, -Ed

Serialization Snippet

Public Sub SaveApplicationOptions(ByVal AppOptions As ApplicationOptions) Implements IApplicationOptionsRepository.SaveApplicationOptions
  Dim serializer As New XmlSerializer(GetType(ApplicationOptions))
  Dim ApplicationOptionsFilename As String = ConfigurationManager.AppSettings("ApplicationOptionsXML")
  Dim sw As New StreamWriter(ApplicationOptionsFilename)
  serializer.Serialize(sw, AppOptions)
  sw.Close()
  sw.Dispose()
End Sub
+1  A: 

The problem might be in the two characters used for new lines -- the linefeed character and the carriage return character. Windows, UNIX and Mac all use these differently. XML parsers change new lines to a single linefeed character. This applies for all systems for uniformity.

In your deserialized text, the linefeed codes will likely appear as "\n".

One approach would be to replace the "\n" with a NewLine. For example,

DeserializedText = DeserializedText.Replace("\n", Environment.NewLine);

The linefeed codes will then appear as "\r\n" which will look sensible in the WinForms Textbox.

Lawrence P. Kelley
+2  A: 

Hi there.

Another approach is to use the XmlAttribute(), as mentioned here. For example:

Imports System.Xml.Serialization

Public Class ApplicationOptions

    Private _someText As String = String.Empty

    <XmlAttribute()> _
    Public Property SomeText() As String
        Get
            Return _someText
        End Get
        Set(ByVal value As String)
            _someText = value
        End Set
    End Property

End Class

I just tried it on a sample app and the linefeed characters were not replaced during de-serialisation.

Cheers. Jas.

Jason Evans
+1 Excellent answer. This answer gets to the essence of it. I opted for the selected answer only because my XML will be used elsewhere and the encoded linefeed string () will trip up some other consumers. Cheers!
Ed Lee
Helpful - thanks.
frou