Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate xml file without the header

Tags:

c#

.net

I don't need the header . How to do it with xml serializer?

like image 512
user496949 Avatar asked Feb 26 '23 19:02

user496949


1 Answers

XmlSerializer isn't responsible for that - XmlWriter is, so the key here is to create a XmlWriterSettings object with .OmitXmlDeclaration set to true, and pass that in when constructing the XmlWriter:

using System.Xml;
using System.Xml.Serialization;
public class Foo
{
    public string Bar { get; set; }
}
static class Program
{
    static void Main()
    {
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;
        using (XmlWriter writer = XmlWriter.Create("my.xml", settings))
        {
            XmlSerializer ser = new XmlSerializer(typeof(Foo));
            Foo foo = new Foo();
            foo.Bar = "abc";
            ser.Serialize(writer, foo);
        }

    }
}
like image 134
Marc Gravell Avatar answered Feb 28 '23 16:02

Marc Gravell