如何从大型XML文档中获取流迭代器[Node]



我需要处理由大量独立记录组成的XML文档,例如

<employees>
    <employee>
         <firstName>Kermit</firstName>
         <lastName>Frog</lastName>
         <role>Singer</role>
    </employee>
    <employee>
         <firstName>Oscar</firstName>
         <lastName>Grouch</lastName>
         <role>Garbageman</role>
    </employee>
    ...
</employees>

在某些情况下,这些只是大文件,但在其他情况下,它们可能来自流媒体源。

我不能只是scale .xml. xmlloader .load()它,因为我不想在内存中保存整个文档(或等待输入流关闭),当我只需要一次处理一条记录时。我知道我可以使用XmlEventReader将输入流化为XmlEvents序列。但是,与scala.xml.Node相比,使用它们要方便得多。

所以我想以某种方式得到一个懒惰的迭代器[Node],以便使用方便的Scala语法对每个单独的记录进行操作,同时保持内存使用在控制之下。

要自己做这件事,我可以从一个XmlEventReader开始,在每个匹配的开始和结束标记之间建立一个事件缓冲区,然后从中构造一个Node树。但是,有没有一种更简单的方法被我忽略了?谢谢你的建议!

您可以使用XMLEventReaderConstructingParser使用的底层解析器,并通过回调处理顶层以下的雇员节点。您只需要在处理完数据后小心地丢弃数据:

import scala.xml._
def processSource[T](input: Source)(f: NodeSeq => T) {
  new scala.xml.parsing.ConstructingParser(input, false) {
    nextch // initialize per documentation
    document // trigger parsing by requesting document
    var depth = 0 // track depth
    override def elemStart(pos: Int, pre: String, label: String,
        attrs: MetaData, scope: NamespaceBinding) {
      super.elemStart(pos, pre, label, attrs, scope)
      depth += 1
    }
    override def elemEnd(pos: Int, pre: String, label: String) {
      depth -= 1
      super.elemEnd(pos, pre, label)
    }
    override def elem(pos: Int, pre: String, label: String, attrs: MetaData,
        pscope: NamespaceBinding, nodes: NodeSeq): NodeSeq = {
      val node = super.elem(pos, pre, label, attrs, pscope, nodes)
      depth match {
        case 1 => <dummy/> // dummy final roll up
        case 2 => f(node); NodeSeq.Empty // process and discard employee nodes
        case _ => node // roll up other nodes
      }
    }
  }
}

然后像这样在固定内存中处理第二级的每个节点(假设第二级的节点没有获得任意数量的子节点):

processSource(src){ node =>
  // process here
  println(node)
}

XMLEventReader相比,好处是不需要使用两个线程。此外,与建议的解决方案相比,您不必解析节点两次。缺点是这依赖于ConstructingParser的内部工作。

要从huynhjl的生成器解决方案获得TraversableOnce[Node],请使用以下技巧:

def generatorToTraversable[T](func: (T => Unit) => Unit) = 
  new Traversable[T] {
    def foreach[X](f: T => X) {
      func(f(_))
    }
  }
def firstLevelNodes(input: Source): TraversableOnce[Node] =
  generatorToTraversable(processSource(input))

generatorToTraversable的结果不能遍历一次以上(即使在每次foreach调用上实例化了一个新的ConstructingParser),因为输入流是Source,而Source是Iterator。我们不能重写Traversable。istraversable因为它是final

实际上,我们希望通过返回一个Iterator来实现这一点。然而,两者都是可遍历的。toIterator和Traversable.view.toIterator创建一个中间流,它将缓存所有条目(违背了本练习的全部目的)。哦;我只是让流抛出一个异常,如果它被访问了两次。

还要注意的是,整个事情不是线程安全的。

这段代码运行得很好,我相信整体解决方案既懒惰又不缓存(因此内存恒定),尽管我还没有在大输入上尝试过。

最新更新