How can I make the xmlserializer only serialize plain xml?

Grzenio picture Grzenio · Nov 20, 2009 · Viewed 58.4k times · Source

I need to get plain xml, without the <?xml version="1.0" encoding="utf-16"?> at the beginning and xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" in first element from XmlSerializer. How can I do it?

Answer

Simon Sanderson picture Simon Sanderson · Sep 17, 2010

To put this all together - this works perfectly for me:

    // To Clean XML
    public string SerializeToString<T>(T value)
    {
        var emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
        var serializer = new XmlSerializer(value.GetType());
        var settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.OmitXmlDeclaration = true;

        using (var stream = new StringWriter())
        using (var writer = XmlWriter.Create(stream, settings))
        {
            serializer.Serialize(writer, value, emptyNamespaces);
            return stream.ToString();
        }
    }