How to keep XmlSerializer from killing NewLines in Strings?

后端 未结 5 1891
迷失自我
迷失自我 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条回答
  •  Happy的楠姐
    2020-12-08 07:04

    It is not the XmlSerializer but the XmlWriter which is removing your CR. To retain it we must have the writer convert CR to its character entity .

    XmlWriterSettings ws = new XmlWriterSettings();
    ws.NewLineHandling = NewLineHandling.Entitize;
    
    XmlSerializer ser = new XmlSerializer( typeof( Abc ) );
    using (XmlWriter wr = XmlWriter.Create( "abc.xml", ws )) {
        ser.Serialize( wr, s );
    }
    

    This is exactly the same with DataContractSerializer:

    var ser = new DataContractSerializer( typeof( Abc ) );
    using (XmlWriter wr = XmlWriter.Create( "abc.xml", ws )) {
        ser.Serialize( wr, s );
    }
    

    Why do we need to do this?

    This is because compliant XML parsers must, before parsing, translate CRLF and any CR not followed by a LF to a single LF. This behavior is defined in the End-of-Line handling section of the XML 1.0 specification.

    As this happens before parsing, you need to encode CR as its character entity if you want the CR to exist in the document.

提交回复
热议问题