Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 不调用XmlWriter.WriteEntDocument()而使用XmlWriter.WriteEndDocument()是否可行_C#_.net_Xml_Xmlwriter - Fatal编程技术网

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非常罕见),谢谢你的回答。这个很有用。