我想知道XmlWriter.WriteStartDocument()
和XmlWriter.WriteEndDocument()
背后的原因。
在我的场景中,我正在创建一个包含一些数据的XML文档,例如:
XmlWriter xmlWriter = XmlWriter.Create(file);
xmlWriter.WriteStartDocument();
// write xml elements and attributes...
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
在序列化时,如果我们跳过对XmlWriter
的调用并且最后只调用xmlWriter.WriteStartDocument()
,则xmlWriter.WriteEndDocument()
不会抛出任何异常。
以下代码段不会抛出任何错误或异常:
XmlWriter xmlWriter = XmlWriter.Create(file);
// write xml elements and attributes...
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
这怎么可能?您能解释一下WriteStartDocument()
和WriteEndDocument()
的功能吗?
答案 0 :(得分:3)
t1
的每the documentation,此方法会写出在根元素::
在派生类中重写时,编写XML声明。
matricule
的{{1}}:
在派生类中重写时,关闭所有打开的元素或属性,并将编写器重新置于“开始”状态。
没有提及任何一方与另一方有关或依赖另一方,实际上你的实验似乎证明了这一点。
与其他类似命名的方法对(如presence
和t1
不同,在没有其他方法的情况下调用其中一个方法对无法使您进入文档无效的状态。也就是说,我仍然建议你在编写文档的开始和结束时调用它们,因为这显然是API打算你做的。
顺便说一句,很少需要像这样直接使用matricule
和WriteStartDocument
。它们是非常低级的XML API。我建议您在大多数用例中探索LINQ to XML和WriteEndDocument
。