Maintain whitespace/line breaks when serializing v

2019-04-01 00:46发布

问题:

I'm doing some pre-processing of an XML document in a ASMX Webservice (Legacy .NET SOAP Service) for eventual use in a Silverlight front end.

I'm processing that XML document into a POCO object for ease of use. The object is defined as follows:

public class CACDocument : ITextDocument
{
    #region Properties
    public string Title { get; set; }
    public string Text { get; set; }
    public List<Code> CodeList { get; set; }
    public XElement FormatedText { get; set; }
    #endregion

    #region Constructor
    public CACDocument()
    {
        CodeList = new List<Code>();
    }
    #endregion
}

The Text property in that object contains basically formatted text (line breaks, white space, etc...). The XML node that feeds that property looks like this:

<text>
   A TITLE FOLLOWED BY two line breaks


   Some text followed by a line break

   Some more text that might extend for a paragraph or two followed by more line breaks

   Still more text
</text>

All is fine and format is maintained as I would expect up unitl the Web Services serializes the data to be sent out to the front end. I'm guessing that in an attempt to optimize bandwidth, the serialized object strips the extra whitespace and line breaks from the Text property before sending it out. In this one particular instance, that formatting is important. Is there a way to force the webservice to maintain this whitespace/line break formatting?

I imagine that I code substitute some coding for the items in question, and then convert back on the front end, but that strikes me as a bit of a kludge.

回答1:

You can serialize it as a CDATA section :

    [XmlIgnore]
    public string Text { get; set; }

    private static readonly XmlDocument _xmlDoc = new XmlDocument();

    [XmlElement("Text")]
    public XmlCDataSection TextCData
    {
        get
        {
            return _xmlDoc.CreateCDataSection(Text);
        }
        set
        {
            Text = value.Data;
        }
    }

The text will be serialized like that :

<text><![CDATA[A TITLE FOLLOWED BY two line breaks


   Some text followed by a line break

   Some more text that might extend for a paragraph or two followed by more line breaks

   Still more text]]></text>


回答2:

I presume you're referring to ASMX web services?

Actually, I don't think there's a way to do this without serializing as a byte array. Alternatively, you could implement IXmlSerializable and do all the work yourself.


You'll want something like this:

public class CACDocument : ITextDocument {
    // ...
    [XmlIgnore]
    public string Text {get;set;}

    [XmlText]
    public byte[] TextSubstitute {
        get {return System.Text.Encoding.UTF8.GetBytes(Text);}
        set {Text = System.Text.Encoding.UTF8.GetString(value);}
    }
}

That's not tested, but you'll get the idea. You can also use [XmlElement] instead of [XmlText], and specify a different element name.