Omitting XML processing instruction when serializing an object

Dan R picture Dan R · Oct 2, 2008 · Viewed 12.5k times · Source

I'm serializing an object in a C# VS2003 / .Net 1.1 application. I need it serialized without the processing instruction, however. The XmlSerializer class puts out something like this:

<?xml version="1.0" encoding="utf-16" ?> 
<MyObject>
    <Property1>Data</Property1>
    <Property2>More Data</Property2>
</MyObject>

Is there any way to get something like the following, without processing the resulting text to remove the tag?

<MyObject>
    <Property1>Data</Property1>
    <Property2>More Data</Property2>
</MyObject>

For those that are curious, my code looks like this...

XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
StringBuilder builder = new StringBuilder();

using ( TextWriter stringWriter = new StringWriter(builder) )
{
    serializer.Serialize(stringWriter, comments);
    return builder.ToString();
}

Answer

JonF picture JonF · Nov 26, 2008

I made a small correction

XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
StringBuilder builder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
using ( XmlWriter stringWriter = XmlWriter.Create(builder, settings) )
{   
   serializer.Serialize(stringWriter, comments);  
  return builder.ToString();
}