如何在序列化时跳过xml声明?

我试图输出一个没有xml头的xml文件,就像我试过的那样:

Type t = obj.GetType(); XmlSerializer xs=new XmlSerializer(t); XmlWriter xw = XmlWriter.Create(@"company.xml", new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true }); xs.Serialize(xw,obj); xw.Close(); 

但它仍然在xml文件中输出。 我不想要字符串技巧。 有任何想法吗?

ConformanceLevel设置为Fragment ,如下所示:

 Type t = obj.GetType(); XmlSerializer xs=new XmlSerializer(t); XmlWriter xw = XmlWriter.Create(@"company.xml", new XmlWriterSettings() { OmitXmlDeclaration = true , ConformanceLevel = ConformanceLevel.Auto , Indent = true }); xs.Serialize(xw,obj); xw.Close(); 

看看文档 。 在那里你看到了

如果将ConformanceLevel设置为Document,则始终会写入XML声明,即使OmitXmlDeclaration设置为true也是如此。

如果ConformanceLevel设置为Fragment,则永远不会写入XML声明。 您可以调用WriteProcessingInstruction来显式写出XML声明。

所以你需要添加

 ConformanceLevel = ConformanceLevel.Fragment; 

如果使用Serialize重载(Stream,Object,XmlSerializerNamespaces)并将null作为XmlSerializerNamespaces提供,则XmlSerializer将不会尝试失败的WriteStartDocument。 尝试:

 xs.Serialize(xw, obj, null);