【问题标题】:How can I skip xml declaration when serializing?序列化时如何跳过 xml 声明?
【发布时间】:2012-03-09 02:34:14
【问题描述】:

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

【问题讨论】:

  • 你为什么要做这样的事情,我只是好奇:)?
  • 在so上发现了类似的东西,看看:stackoverflow.com/questions/933664/…
  • 可能会输出一些片段,这些片段稍后会添加到文档中?或者也许像 XMPP 那样通过套接字发送 XML 片段?很多用处:)
  • 别忘了处理 XmlWriter(最好用 using 语句包装)

标签: c# xml serialization


【解决方案1】:

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

【讨论】:

  • 谢谢,但我收到此错误:System.InvalidOperationException: WriteStartDocument 无法在使用 ConformanceLevel.Fragment 创建的编写器上调用。
  • @orange 我抛出了同样的异常,但是设置 OmitXmlDeclaration = true 并明确设置 ConformanceLevel = ConformanceLevel.Auto 得到了预期的结果。
  • @Grx70 我也遇到了同样的问题,您的修复也对我有用,谢谢。
【解决方案2】:

查看documentation。 你看到了

如果 ConformanceLevel 设置为 文档,即使 OmitXmlDeclaration 设置为 true。

如果 ConformanceLevel 设置为 分段。您可以调用 WriteProcessingInstruction 显式编写 出一个 XML 声明。

所以你需要添加

ConformanceLevel = ConformanceLevel.Fragment;

【讨论】:

  • 我试过ConformanceLevel = ConformanceLevel.Fragment,但序列化失败。然而ConformanceLevel = ConformanceLevel.Auto 就像一个魅力(就像它写在迭戈的答案中一样)
【解决方案3】:

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

xs.Serialize(xw, obj, null);

【讨论】:

  • 这也有效。如果您通过实现 IXmlSerializable 接口来自定义序列化对象链的一部分,那么您已经有一个 XmlWriter,所以这个解决方案变得更简单。
猜你喜欢
  • 2012-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-09
  • 1970-01-01
相关资源
最近更新 更多