XDocument.Load 是否将所有数据加载到内存中? [英] Does XDocument.Load loads all data into memory?

查看:39
本文介绍了XDocument.Load 是否将所有数据加载到内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须读取如下所示的大型 xml 文件根节点的所有一级节点:

I must read all first level nodes of the root node of large xml file that looks like the following:

<root>
 <record n="1"><a/><b/><c/></record>
 <record n="2"><a/><b/><c/></record>
 <record n="3"><a/><b/><c/></record>
</root>

我的代码如下:

var xml = XDocument.Load(filename);

var firstNode = xml?.Root?.Descendants()?.FirstOrDefault();

var elements = firstNode?.Elements();

我只需要获取根的第一个孩子和它的所有一级后代.这段代码工作正常,但问题是:这样阅读是否安全?我猜它不会将所有数据加载到内存中——只有 xml 文件的结构?

I just need to get the first child of the root and all first level descendants of it. This code works fine, but the question is: is it safe to read like this? I guess it does not load all data into memory - only the structure of the xml file?

正如我所见,调试时内存没有增加.如果我真的尝试查看 xml 变量中的内容,它只会爆炸.

As I see memory is not increased while debugging. It only explodes if I actually try to see what is in xml variable.

推荐答案

不,XDocument 将整个文档加载到内存中.这样做是否安全"取决于您需要处理的文档大小.

No, XDocument loads the whole document into memory. Whether it's "safe" to do this or not depends on what size of document you need to be able to handle.

如果您需要处理无法放入内存的 XML 文件,您应该使用 XmlReader,不幸的是,它很难使用.

If you need to handle XML files that wouldn't fit into memory, you'd want to use XmlReader, which is unfortunately considerably harder to use.

这篇关于XDocument.Load 是否将所有数据加载到内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆