XmlReader和XElement组合之读取大型xml文档

简介

在.NET framework 中存在大量操作xml数据的类库和api,但在.NET framework 3.5后我们的首选一般就是linq to xml。

linq to xml操作xml数据无论是XElement.Load方法还是XElement.Parse方法都会将整个xml文件加载到内存中,在xml文件超级大的情况下linq to xml就不太适合。

对于大型的xml文件最好的方法就是每次只读取一部分,这样逐渐的读取整个xml文件,这个刚好对应XmlReader类。

XmlReader使用起来效率高,但操作没有linq to xml方便,所以就希望取两者之长:既有效率使用起来也如linq to xml一样方便。

思路

XElement类有一个方法ReadFrom,此方法接受一个XmlReader参数 : XNode.ReadFrom 方法 (XmlReader)

在上面的链接MSDN上,其实已经有了对应的组合方式了,而且名字也不错:执行大型 XML 文档的流式转换

static IEnumerable<XElement> StreamXElements(string uri, string matchname)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
settings.IgnoreWhitespace = true; using (XmlReader reader = XmlReader.Create(uri, settings))
{
reader.MoveToContent();
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (reader.Name == matchname)
{
XElement el = XElement.ReadFrom(reader) as XElement;
if (el != null)
{
yield return el;
}
}
break; }
}
}
}

以上代码就是用XmlReader一直Read下去,然后碰到XmlNodeType.Element类型时就可以XElement.ReadFrom(reader)构建XElement,最重要的就是最后的yield return。

这样目前为止,so far so good.

但在测试的时候,发现此方法有一个比较严重的bug,每次读取一个XElement之后就会跳过一个XElement:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAANkAAACnCAIAAAAT9G6QAAAJHElEQVR4nO2dvXHsNhSF4Qo8L3EDnjeuwQifK3guAnUodGZknHEDijZlAVvEJixBiZ05wwvAH/xcUuDP7r0EzzcMJAgEoOXRIcDF0SoHgAwU9wAA6IEWgRSgRSAFaBFIAVoEUoAWgRSgRSAFaBFIAVoEUpClxYdRb0q9KXVrd7bU3pS+dwf13tnmgCGBT9iqxdb4y+aPxq687Et0d32gFttbMM43bT+29L5F2cOJQe8Gcl5inRY765Rx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kHfZTqW+yAPyLruALx4E8i67gS8CMUAQQArwRSAFCAJIAb4IpABBACnAF4EUIAggBDxfDEDehZX633dB3iXdx8CbdxmL8y0bdfoi8i75OZLyLvT2oQp9EXkXuXmX8eUTpcUn+SLyLpLzLuGABGnxGSDv4mTnXaizp0q1+SLyLtSyQkzexdEN+DpV+aIHeRfBeRc3VhKkRY51dADyLtHjl5flXaKHPyoOwlToi5wg77KdSn2RB+RddgFfPAjkXXYDXwRigCCAFOCLQAoQBJACfBFIAYIAUoAvAilAEEAIeL4YgLwLK/W/74K8S7oRgTXvQp/uq9fpi8i75OfIyLuQp/ffV+iLyLuIz7vEpw/f1+aLyLucIe8SnT4WVOWLyLu4c+Rd6M3htfki8i7UskJW3oXcbF6bL3qQd5Gcd5kRoqvQFz3Iu4xVheVdZk53rk5f5AR5l+1U6os8IO+yC/jiQSDvshv4IhADBAGkAF8EUoAggBTgi0AKEASQAnwRSAGCAELA88UA5F1Yqf99F+Rd0o0IvJ/vEhZK2Uv7VF9E3iU/B3kXBpB3OUXeJdvoWJ0vIu8iPu8yFKejrMsXkXdxJ8m79GfVnQNE3oVaVsjKu8wU1uWLHuRdJOddwt9O1+2LHuRdxqqC8y7JwGr0RU6Qd9lOpb7IA/Iuu4AvHgTyLruBLwIxQBBACvBFIAUIAkgBvgik8AMeU9Al42Ag7gAAAABJRU5ErkJggg==" alt="" />

如以上的xml,在读取第一个470002048节点之后,470002049节点就被跳过了。

这里其实就是XmlReader不小心Read too far的一个问题,read too far其实就是多read了一次,可以这样理解:

initial read;
(while "we're not at the end") {
do stuff;
read;
}

再回到我们上面的代码,其实在XElement.ReadFrom(reader)构建XElement之后,内部已经read了一次,但在while语句中我们还是在reader,这样下一个XElement是不会读到的。

那知道原因之后,解决起来也简单了,这里就用reader.EOF 做判断条件并去掉多余的一次read,具体代码如下:

static IEnumerable<XElement> StreamXElements(string uri, string matchname)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
settings.IgnoreWhitespace = true; using (XmlReader reader = XmlReader.Create(uri, settings))
{
reader.MoveToContent();
while (!reader.EOF)
{
if (reader.NodeType == XmlNodeType.Element
&& reader.Name == matchname)
{
XElement el = XElement.ReadFrom(reader) as XElement;
if (el != null)
{
yield return el;
}
}
else
{
reader.Read();
}
}
}
}

总结

组合XmlReader和XElement的方式在MSDN中其实已经有了相应的文章介绍,但自己摸索的过程中还是有很多的收获,参考文章如下:

http://*.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator

https://msdn.microsoft.com/en-us/library/mt693229.aspx

http://*.com/questions/2441673/reading-xml-with-xmlreader-in-c-sharp

https://blogs.msdn.microsoft.com/xmlteam/2007/03/24/streaming-with-linq-to-xml-part-2/

上一篇:C和指针 第十一章 习题


下一篇:匹克定理pick