在不调用 XmlWriter.WriteStartDocument() 的情况下使用 XmlWriter.WriteEndDocument() 是否可行

Is it feasible to use XmlWriter.WriteEndDocument() without calling XmlWriter.WriteStartDocument()

我想知道 XmlWriter.WriteStartDocument()XmlWriter.WriteEndDocument() 背后的原因。

在我的场景中,我正在创建一个 XML 文档,其中包含一些数据,例如:

XmlWriter xmlWriter = XmlWriter.Create(file);

xmlWriter.WriteStartDocument();

// write xml elements and attributes...

xmlWriter.WriteEndDocument();

xmlWriter.Flush();

在序列化时,如果我们跳过对 xmlWriter.WriteStartDocument() 的调用并在最后调用 xmlWriter.WriteEndDocument()XmlWriter 不会抛出任何异常。

下面的代码片段没有抛出任何错误或异常:

XmlWriter xmlWriter = XmlWriter.Create(file);

// write xml elements and attributes...

xmlWriter.WriteEndDocument();

xmlWriter.Flush();

这怎么可能?你能解释一下 WriteStartDocument()WriteEndDocument() 的功能吗?

Per the documentation for WriteStartDocument,此方法写入出现在根元素之前的 XML 声明::

When overridden in a derived class, writes the XML declaration.

根据 the documentation WriteEndDocument:

When overridden in a derived class, closes any open elements or attributes and puts the writer back in the Start state.

没有提到任何一个与另一个相关或依赖于另一个,而且你的实验似乎确实证明了这一点。

WriteStartElementWriteEndElement 等其他类似命名的方法对不同,调用其中一个而不调用另一个不会使您进入文档无效的状态。也就是说,我仍然建议您在撰写文档的开始和结束时调用它们,因为这显然是 API 想要您做的。

顺便说一句,很少需要像这样直接使用 XmlReaderXmlWriter。他们是很低级的 XML APIs。对于大多数用例,我建议您探索 LINQ to XML 和 XmlSerializer