C# 和读取大型 XML 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12931769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# and Reading Large XML Files
提问by IEnumerable
I know, I know this has been done to death; Im just posting a question to see if this solution is still relevant since now we have .NET 4 and newer
我知道,我知道这已经是死了;我只是发布一个问题,看看这个解决方案是否仍然相关,因为现在我们有 .NET 4 和更新版本
This linkexplain a simple way to read large XML files and it implements Linq. I quite like this and just want a simple answer/s to state if this is still relevant or are there better implementations in newer .NET code.
此链接解释了一种读取大型 XML 文件的简单方法,它实现了 Linq。我非常喜欢这个,只是想要一个简单的答案来说明这是否仍然相关或者在较新的 .NET 代码中是否有更好的实现。
采纳答案by James
The answer to this question hasn't changed in .NET 4 - for best performance you should still be using XmlReaderas it streamsthe document instead of loading the full thing into memory.
这个问题的答案在 .NET 4 中没有改变 - 为了获得最佳性能,您仍然应该使用XmlReader,因为它流式传输文档而不是将整个内容加载到内存中。
The code you refer to uses XmlReaderfor the actual querying so should be reasonably quick on large documents.
您引用的代码XmlReader用于实际查询,因此在大型文档上应该相当快。
回答by Ekk
The best way to do this is read it line by line using XmlReader.Create.
最好的方法是使用XmlReader.Create逐行读取它。
var reader = XmlReader.Create(filename);
reader.WhitespaceHandling = WhitespaceHandling.None;
while (reader.Read())
{
// your code here.
}
回答by Stas BZ
If it seems like this:
如果看起来像这样:
<root>
<item>...</item>
<item>...</item>
...
</root>
you can read file with XmlReaderand each 'item' open with XmlDocumentlike this:
您可以使用以下方式读取文件,XmlReader并使用XmlDocument以下方式打开每个“项目” :
reader.ReadToDescendant("root");
reader.ReadToDescendant("item");
do
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(reader.ReadOuterXml());
XmlNode item = doc.DocumentElement;
// do your work with `item`
}
while (reader.ReadToNextSibling("item"));
reader.Close();
In this case, you have no limits on file size.
在这种情况下,您对文件大小没有限制。
回答by Anjan Kant
I was struggling with the same issue from last few days. I just right clickon project propertiesthen navigated to Build taband select option Any CPU, tick uncheckoption Prefer 32 Bitand save it before to run your app, it helped me. I have attached snapshot of the same.

过去几天我一直在努力解决同样的问题。我只是右键单击在项目属性,然后导航到Build选项卡并选择选项任何CPU,勾选取消选中选项身高32位,并将其保存之前运行你的应用程序,它帮助我。我附上了相同的快照。


