views:

309

answers:

2

I'm using XmlSerializer.Serialize, and it produces line breaks and unnecessary spaces. How to avoid it?

+2  A: 

Perhaps you could use the overload accepting an XmlWriter, and configure the given XmlWriter with an XmlWriterSettings instance?

XmlWriterSettings allows you to control the application of line breaks and indentation.

void Serialize(Object o)
{
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = false;
    settings.NewLineHandling = NewLineHandling.None;
    //settings.OtherProperties = values;

    using (XmlWriter writer = XmlWriter.Create(CreateStream(), settings))
    {
        _serializer.Serialize(o, writer);
    }
}
Steve Guidi
it worked, thanks
Jader Dias
+1  A: 

It's interesting, I thought there was no formatting by default. I just tried the following and got no formatting:

using (var stream = new MemoryStream())
{
    System.Text.Encoding encoding;
    using (var writer = XmlWriter.Create(stream))
    {
        if (writer == null)
        {
            throw new InvalidOperationException("writer is null");
        }

        encoding = writer.Settings.Encoding;
        var ser = new XmlSerializer(obj.GetType());
        ser.Serialize(writer, obj);
    }

    stream.Position = 0;
    using (var reader = new StreamReader(stream, encoding, true))
    {
        return reader.ReadToEnd();
    }
}

in a sample run, it returned the following XML:

<?xml version="1.0" encoding="utf-8"?><obj xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;&lt;childOne /><childTwo /><text>text1</text><text>text2</text></obj>
John Saunders
Maybe it likes you more =)
Jader Dias
Such an inconsistency should be reported to Microsoft. A method cannot behave in different ways. It's CultureInfo dependent? Or it's a .NET Version/Service Pack? I don't know yet.
Jader Dias
If you get a chance, run the code I posted. I'm running .NET 3.5 SP1. Let's see what the real difference is.
John Saunders