ScArcher2
ScArcher2

Reputation: 87257

How do I parse an xml document as a stream using Scala?

How do I parse an xml document as a stream using Scala? I've used the Stax API in java to accomplish this, but I'd like to know if there is a "scala" way to do this.

Upvotes: 18

Views: 9244

Answers (2)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297265

Use package scala.xml.pull. Snippet taken from the Scaladoc for Scala 2.8:

import scala.xml.pull._
import scala.io.Source
object reader {
  val src = Source.fromString("<hello><world/></hello>")
  val er = new XMLEventReader(src)
  def main(args: Array[String]) {
    while (er.hasNext)
      Console.println(er.next)
  }
}

You can call toIterator or toStream on er to get a true Iterator or Stream.

And here's the 2.7 version, which is slightly different. However, testing it seems to indicate it doesn't detect the end of the stream, unlike in Scala 2.8.

import scala.xml.pull._
import scala.io.Source

object reader {
  val src = Source.fromString("<hello><world/></hello>")
  val er = new XMLEventReader().initialize(src)

  def main(args: Array[String]) {
    while (er.hasNext)
      Console.println(er.next)
  }
}

Upvotes: 29

Randall Schulz
Randall Schulz

Reputation: 26486

scala.xml.XML.loadFile(fileName: String)
scala.xml.XML.load(url: URL)
scala.xml.XML.load(reader: Reader)
scala.xml.XML.load(stream: InputStream)

There are others...

Upvotes: -2

Related Questions