开发者

XmlSerializer Converts newlines

开发者 https://www.devze.com 2023-02-13 07:55 出处:网络
I\'m trying to serialize an object to memory, pass it to another process as a string, and deserialize it.

I'm trying to serialize an object to memory, pass it to another process as a string, and deserialize it.

I've discovered that the XML Serialization process strips the \r off of the newlines for strings in the object.

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

How do I serialize an object without serializing it to disk just like this, but without mangling the newlin开发者_如何学编程es in the strings?


The strings should be wrapped in CDATA sections to preserve the newlines.


The answer came from anther SO post, but I'm reposting it here because I had to tweak it a little.

I had to create a new class to manage XML read/write to memory stream. Here it is:

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

Since it is built on top of XmlSerializer, it should behave exactly as expected. It's just that when I serialize with a StreamWriter, I will use the "safe" version of the serialization, thus saving myself the headache.

I hope this helps someone else.

0

精彩评论

暂无评论...
验证码 换一张
取 消