C# 不调用XmlWriter.WriteEntDocument()而使用XmlWriter.WriteEndDocument()是否可行
我想知道C# 不调用XmlWriter.WriteEntDocument()而使用XmlWriter.WriteEndDocument()是否可行,c#,.net,xml,xmlwriter,C#,.net,Xml,Xmlwriter,我想知道XmlWriter.WriteStartDocument()和XmlWriter.WriteEndDocument()背后的原因 在我的场景中,我正在创建一个包含一些数据的XML文档,例如: XmlWriter xmlWriter = XmlWriter.Create(file); xmlWriter.WriteStartDocument(); // write xml elements and attributes... xmlWriter.WriteEndDocument();
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()
的功能吗?对于WriteStartDocument
,此方法写入显示在根元素之前的XML声明:
在派生类中重写时,写入XML声明
对于写入的文档
,请参见:
在派生类中重写时,关闭所有打开的元素或属性,并将编写器恢复到开始状态
没有提到两者之间有联系或相互依赖,事实上,你的实验似乎证明了这一点
与其他类似命名的方法对(如writeStarteElement
和WriteEndElement
)不同,调用其中一个方法而不调用另一个方法不能使您进入文档无效的状态。尽管如此,我仍然建议您在编写文档的开始和结束时调用它们,因为这显然是API打算让您做的事情
另外,很少需要像这样直接使用
XmlReader
和XmlWriter
。它们是非常低级的XML API。我建议您在大多数用例中探索LINQ to XML和XmlSerializer
。@stuartd但在C#中,仅使用WriteEndDocument()就可以了。@stuartd我的问题是“为什么将XML声明写入文件时不需要这两条语句?”。仅“WriteEndDocument()”就足以编写xml声明。这似乎有点奇怪。@stuartd在XML1.0中(这是最常用的,1.1非常罕见),谢谢你的回答。这个很有用。