gpt4 book ai didi

c# - 将大量 xml 数据写入文件的最佳方法?

转载 作者:数据小太阳 更新时间:2023-10-29 02:15:15 27 4
gpt4 key购买 nike

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

_XmlTextWriterObject = new XmlTextWriter(_xmlFilePath, null);

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

编辑

抱歉,我无法真正表达我的意思。感谢 Ash 指出。我确实会使用 XmlTextWriter 但我的意思是说是将物理文件路径字符串传递给 XmlTextWriter 构造函数(或者,如 John 所建议的那样,传递给 XmlTextWriter.Create() 方法)还是使用基于流的接口(interface)。我当前的代码如下所示:

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
}

最佳答案

经验法则是当文档只需要写入而不是在内存中使用时使用XmlWriter,并在您需要的地方使用XmlDocument(或DOM)确实需要在内存中使用它。

不过请记住,XmlWriter 实现了 IDisposable,因此请执行以下操作:

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

关于c# - 将大量 xml 数据写入文件的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2673116/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com