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

时间:2012-02-17 17:11:48

标签: c# xml serialization

我正在尝试输出没有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文件中输出。 我不想要字符串技巧。有什么想法吗?

3 个答案:

答案 0 :(得分:21)

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

答案 1 :(得分:4)

查看documentation。 你看到了

  

如果将ConformanceLevel设置为,则始终会写入XML声明   文档,即使OmitXmlDeclaration设置为true。

     

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

所以你需要添加

ConformanceLevel = ConformanceLevel.Fragment;

答案 2 :(得分:1)

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

xs.Serialize(xw, obj, null);