Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize a .net object and omit the doctype?

I've written some .net code to serialize an object using the XMLSerializer class.

    public static string serialize(object o)
    {
            Type type = o.GetType();
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);                
            System.IO.StringWriter writer = new System.IO.StringWriter();
            serializer.Serialize(writer, o);                
            return writer.ToString();         
    }

The output looks like this:

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <string>a</string>
  <string>b</string>
  <string>c</string>
</ArrayOfString>

That's great, but what I would really like is to get just the root node without the XML doctype declaration at the beginning.

The reason I want to do this is because I would like to use the root element of the XML serialized object as part of another XML document.

like image 580
Vivian River Avatar asked Oct 04 '12 14:10

Vivian River


1 Answers

XmlWriterSettings has a property to omit the XML declaration (OmitXmlDeclaration):

public static string Serialize(object obj)
{
    var builder = new StringBuilder();
    var xmlSerializer = new XmlSerializer(obj.GetType());
    using (XmlWriter writer = XmlWriter.Create(builder,
        new XmlWriterSettings() { OmitXmlDeclaration = true }))
    {
        xmlSerializer.Serialize(writer, obj);
    }
    return builder.ToString();
}
like image 125
Paolo Moretti Avatar answered Nov 11 '22 03:11

Paolo Moretti