How can I make the xmlserializer only serialize plain xml?

C#.NetXml SerializationXml Declaration

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

Use the XmlSerializer.Serialize method overload where you can specify custom namespaces and pass there this.

var emptyNs = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
serializer.Serialize(xmlWriter, objectToSerialze, emptyNs);

passing null or empty array won't do the trick

Solution 3 - C#

You can use XmlWriterSettings and set the property OmitXmlDeclaration to true as described in the msdn. Then use the XmlSerializer.Serialize(xmlWriter, objectToSerialize) as described here.

Solution 4 - C#

This will write the XML to a file instead of a string. Object ticket is the object that I am serializing.

Namespaces used:

using System.Xml;
using System.Xml.Serialization;

Code:

XmlSerializerNamespaces emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });

XmlSerializer serializer = new XmlSerializer(typeof(ticket));

XmlWriterSettings settings = new XmlWriterSettings
{
    Indent = true,
    OmitXmlDeclaration = true
};

using (XmlWriter xmlWriter = XmlWriter.Create(fullPathFileName, settings))
{
    serializer.Serialize(xmlWriter, ticket, emptyNamespaces); 
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGrzenioView Question on Stackoverflow
Solution 1 - C#Simon SandersonView Answer on Stackoverflow
Solution 2 - C#kossibView Answer on Stackoverflow
Solution 3 - C#tobsenView Answer on Stackoverflow
Solution 4 - C#Keith AymarView Answer on Stackoverflow