XmlSerializer转换换行符

时间:2011-02-26 02:41:37

标签: c# winforms xml-serialization

我正在尝试将对象序列化为内存,将其作为字符串传递给另一个进程,然后对其进行反序列化。

我发现XML序列化过程会删除对象中字符串换行符的\ r \ n。

byte[] b;
// serialize to memory.
using (MemoryStream ms = new MemoryStream())
{
    XmlSerializer xml = new XmlSerializer(this.GetType());
    xml.Serialize(ms, this);
    b = ms.GetBuffer();
}

// I can now send the bytes to my process.
Process(b);

// On the other end, I use:
using (MemoryStream ms = new MemoryStream(b))
{
    XmlSerializer xml = new XmlSerializer(this.GetType());
    clone = (myObject)xml.Deserialize(ms);
}

如何在没有像这样将其序列化到磁盘的情况下序列化对象,但不会破坏字符串中的换行符?

2 个答案:

答案 0 :(得分:0)

字符串应包含在CDATA部分中以保留换行符。

答案 1 :(得分:0)

答案来自花药SO帖子,但我在这里重新发布,因为我不得不稍微调整一下。

我必须创建一个新类来管理对内存流的XML读/写。这是:

public class SafeXmlSerializer : XmlSerializer
{
    public SafeXmlSerializer(Type type) : base(type) { }

    public new void Serialize(StreamWriter stream, object o)
    {
        XmlWriterSettings ws = new XmlWriterSettings();
        ws.NewLineHandling = NewLineHandling.Entitize;

        using (XmlWriter xmlWriter = XmlWriter.Create(stream, ws))
        {
            base.Serialize(xmlWriter, o);
        }
    }
}

public class SafeXmlSerializer : XmlSerializer { public SafeXmlSerializer(Type type) : base(type) { } public new void Serialize(StreamWriter stream, object o) { XmlWriterSettings ws = new XmlWriterSettings(); ws.NewLineHandling = NewLineHandling.Entitize; using (XmlWriter xmlWriter = XmlWriter.Create(stream, ws)) { base.Serialize(xmlWriter, o); } } }

由于它是在XmlSerializer之上构建的,因此它应该完全按预期运行。只是当我使用StreamWriter进行序列化时,我将使用序列化的“安全”版本,从而避免了头痛。

我希望这有助于其他人。