问题描述
我想解析Wikimedia的.xml.bzip2转储,而不提取整个文件或执行任何XML验证:
I'd like to parse Wikimedia's .xml.bzip2 dumps without extracting the entire file or performing any XML validation:
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
时,当我尝试执行读取操作时会失败:
The BZip2InputStream
works - if I use a StreamReader
, I can read XML line by line. But when I use XmlTextReader
, it fails when I try to perform the read:
bzip流在EOF处为 not 。是否可以在BZip2流顶部打开XmlTextReader?还是有其他方法可以做到这一点?
The bzip stream is not at EOF. Is it possible to open an XmlTextReader on top of a BZip2 stream? Or is there some other means to do this?
推荐答案
这应该可行。我使用了XmlReader和Xml Linq的组合。您可以根据需要解析XElement文档。
This should work. I used combination of XmlReader and Xml Linq. You can parse the XElement doc as needed.
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);
}
}
}
}
}
这篇关于读取非常大的.xml.bz2文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!