Omitting XML processing instruction when serializing an object

前端 未结 6 1866
别那么骄傲
别那么骄傲 2020-12-14 23:44

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 somethin

6条回答
  •  再見小時候
    2020-12-15 00:02

    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.

提交回复
热议问题