How to keep XmlSerializer from killing NewLines in Strings?

后端 未结 5 1884
迷失自我
迷失自我 2020-12-08 07:00

Suppose I have a simple Class with just one Member a String.

public class Abc
{
    private String text;

    public String Text
    {
        get { return          


        
5条回答
  •  失恋的感觉
    2020-12-08 07:12

    Nice solution, Lachlan Roche!

    The function below (in VB.NET) uses a StringWriter to return a String, rather than writing the result to a file using an XmlWriter.

      ''' 
      ''' Exports the object data to an XML formatted string.
      ''' Maintains CR characters after deserialization.
      ''' The object must be serializable to work.
      ''' 
    
      Public Function ExportObjectXml(ByVal obj As Object) As String
        If obj Is Nothing Then
          Return String.Empty
        End If
    
        Dim serializer As New XmlSerializer(obj.GetType)
        Dim settings As New XmlWriterSettings With {.NewLineHandling = NewLineHandling.Entitize}
    
        Using output As New StringWriter
          Using writer As XmlWriter = XmlWriter.Create(output, settings)
            serializer.Serialize(writer, obj)
            Return output.ToString
          End Using
        End Using
      End Function
    

提交回复
热议问题