我正在 ASMX Web 服务(遗留 .NET SOAP 服务)中对 XML 文档进行一些预处理,以便最终在 Silverlight 前端中使用。
我正在将该 XML 文档处理成一个 POCO 对象以便于使用。对象定义如下:
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
}
该对象中的 Text 属性包含基本格式化的文本(换行符、空格等)。提供该属性的 XML 节点如下所示:
<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>
一切都很好,格式保持不变,正如我所期望的那样,直到 Web 服务序列化要发送到前端的数据。我猜想为了优化带宽,序列化对象在发送之前从 Text 属性中去除了额外的空格和换行符。在这个特定的例子中,格式很重要。有没有办法强制网络服务保持这种空白/换行符格式?
我想象我用一些代码替换了有问题的项目,然后在前端转换回来,但这让我觉得有点笨拙。
最佳答案
您可以将其序列化为 CDATA 部分:
[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;
}
}
文本将像这样被序列化:
<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>
关于c# - 通过 ASMX Web 服务序列化时保持空格/换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1103749/