如何保持XmlSerializer的从字符串杀换行符?字符串、换行符、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....

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

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 ('rn' 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.

阅读全文

相关推荐

最新文章