简体   繁体   中英

How to generate xml file without the header

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

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

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM