Search code examples
c#.netxml-serializationvisual-studio-2003

Omitting XML processing instruction when serializing an object


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

Solution

  • The following link will take you to a post where someone has a method of supressing the processing instruction by using an XmlWriter and getting into an 'Element' state rather than a 'Start' state. This causes the processing instruction to not be written.

    Suppress Processing Instruction

    If you pass an XmlWriter to the serializer, it will only emit a processing instruction if the XmlWriter's state is 'Start' (i.e., has not had anything written to it yet).

    // Assume we have a type named 'MyType' and a variable of this type named 
    'myObject' 
    System.Text.StringBuilder output = new System.Text.StringBuilder(); 
    System.IO.StringWriter internalWriter = new System.IO.StringWriter(output); 
    System.Xml.XmlWriter writer = new System.Xml.XmlTextWriter(internalWriter); 
    System.Xml.Serialization.XmlSerializer serializer = new 
    System.Xml.Serialization.XmlSerializer(typeof(MyType)); 
    
    
    writer.WriteStartElement("MyContainingElement"); 
    serializer.Serialize(writer, myObject); 
    writer.WriteEndElement(); 
    

    In this case, the writer will be in a state of 'Element' (inside an element) so no processing instruction will be written. One you finish writing the XML, you can extract the text from the underlying stream and process it to your heart's content.