将巨大的xml数据写入文件的最佳方法?

Kay*_*yes 3 c# xml asp.net xmlwriter

我目前正在使用XmlTextWriter类包含大量数据(100000条记录)的数据库表导出到xml文件中,并且我直接写入物理驱动器上的文件.

_XmlTextWriterObject = new XmlTextWriter(_xmlFilePath, null);
Run Code Online (Sandbox Code Playgroud)

虽然我的代码运行正常但我的问题是它是最好的方法吗?我应该首先在内存流中写入整个xml,然后从内存流中将xml文档写入物理文件中吗?在这两种情况下,对内存/性能的影响是什么?

编辑

对不起,我实际上无法表达我的意思.谢谢Ash指出.我确实会使用XmlTextWriter,但我想说是否将物理文件路径字符串传递给XmlTextWriter构造函数(或者,如John建议的那样,传递给XmlTextWriter.Create()方法)或使用基于流的api.我当前的代码如下所示:

XmlWriter objXmlWriter = XmlTextWriter.Create(new BufferedStream(new FileStream(@"C:\test.xml", FileMode.Create, System.Security.AccessControl.FileSystemRights.Write, FileShare.None, 1024, FileOptions.SequentialScan)), new XmlWriterSettings { Encoding = Encoding.Unicode, Indent = true, CloseOutput = true });
using (objXmlWriter)
{
   //writing xml contents here
}
Run Code Online (Sandbox Code Playgroud)

Kyl*_*ndo 9

经验法则是XmlWriter当文档只需要编写而不是在内存中使用时使用,并使用XmlDocument(或DOM)你需要在内存中使用它.

但请记住,XmlWriter实现IDisposable,请执行以下操作:

using (XmlWriter _XmlTextWriterObject = XmlWriter.Create(_xmlFilePath))
{
   // Code to do the write here
}
Run Code Online (Sandbox Code Playgroud)