如何保持XmlSerializer的从字符串杀换行符? [英] How to keep XmlSerializer from killing NewLines in Strings?

查看:467
本文介绍了如何保持XmlSerializer的从字符串杀换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个简单的类只有一个成员的字符串。

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

public class Abc
{
    private String text;

    public String Text
    {
        get { return this.text; }
        set { this.text = value; }
    }
}

现在,当我序列化,然后用可疑的XmlSerializer的反序列化任何包含文本换行('\ r \ n'或Environment.NewLine)转化为'\ N'。

Now when I serialize and then deserialize it with the questionable XmlSerializer any text containing newlines ('\r\n' or Environment.NewLine) are transformed to '\n'.

我如何保持换行符?

推荐答案

这不是XmlSerializer的,但它是消除你的CR的XmlWriter的。为了留住它,我们必须有作家CR转换为其字符实体&放大器;#13;

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 );
}

这是完全一样的DataContractSerializer:

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 );
}

为什么我们要做这个?

这是因为兼容的XML解析器必须分析之前,翻译CRLF,而不是跟着一个LF单个LF任何CR。这种行为在最终的行处理XML 1.0 部分定义规范。

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.

由于这种情况分析之前,你需要连接code CR为字符实体,如果你想在CR文档中存在。

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

这篇关于如何保持XmlSerializer的从字符串杀换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆