读取非常大的.xml.bz2文件

我想在不提取整个文件或执行任何XMLvalidation的情况下解析维基媒体的.xml.bzip2转储:

var filename = "enwiki-20160820-pages-articles.xml.bz2"; var settings = new XmlReaderSettings() { ValidationType = ValidationType.None, ConformanceLevel = ConformanceLevel.Auto // Fragment ? }; using (var stream = File.Open(filename, FileMode.Open)) using (var bz2 = new BZip2InputStream(stream)) using (var xml = XmlTextReader.Create(bz2, settings)) { xml.ReadToFollowing("page"); // ... } 

BZip2InputStream工作 – 如果我使用StreamReader ,我可以逐行读取XML。 但是当我使用XmlTextReader ,它在我尝试执行读取时失败:

System.Xml.XmlException:’发生了意外的文件结束。 以下元素未关闭:mediawiki。 第58行,第1位。’

bzip流不在 EOF。 是否可以在BZip2流上打开XmlTextReader? 或者还有其他方法可以做到这一点吗?

这应该工作。 我使用了XmlReader和Xml Linq的组合。 您可以根据需要解析XElement文档。

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; namespace ConsoleApplication29 { class Program { const string URL = @"https://dumps.wikimedia.org/enwiki/20160820/enwiki-20160820-abstract26.xml"; static void Main(string[] args) { XmlReader reader = XmlReader.Create(URL); while (!reader.EOF) { if (reader.Name != "doc") { reader.ReadToFollowing("doc"); } if (!reader.EOF) { XElement doc = (XElement)XElement.ReadFrom(reader); } } } } }