XmlSerializer对此不负责任 - XmlWriter因此,这里的关键是创建一个设置为true的XmlWriterSettings对象,并在构造时传递:.OmitXmlDeclarationXmlWriter
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)