如何生成没有标头的xml文件

时间:2010-11-18 02:55:36

标签: c# .net

我不需要标题。 如何使用xml序列化程序?

1 个答案:

答案 0 :(得分:7)

XmlSerializer对此不负责任 - XmlWriter,因此,此处的关键是创建一个XmlWriterSettings对象,其中.OmitXmlDeclaration设置为 true ,并在构造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);
        }

    }
}