
[英]XmlWriter.WriteStartDocument() is not outputting the declaration to the file
[英]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()
吗?
根据WriteStartDocument
的文档 ,此方法编写出现在根元素之前的XML声明::
在派生类中重写时,写入XML声明。
根据WriteEndDocument
的文档 :
在派生类中重写时,关闭所有打开的元素或属性,并将编写器重新置于“开始”状态。
没有提到任何一个都与另一个有关或依赖于另一个,事实上你的实验似乎证明了这一点。
与其他类似命名的方法对(如WriteStartElement
和WriteEndElement
,在没有其他方法的情况下调用其中一个不能使您进入文档无效的状态。 也就是说,我仍然建议你在编写文档的开始和结束时调用它们,因为这显然是API打算你做的事情。
另外,很少需要像这样直接使用XmlReader
和XmlWriter
。 它们是非常低级的XML API。 我建议你在大多数用例中探索LINQ to XML和XmlSerializer
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.