How to parse an XML document as a stream using Scala?

How to parse an XML document as a stream using Scala? I used the Stax API in java for this, but I would like to know if there is a "scala" way.

+13
source share
2 answers

Use the scala.xml.pull package. Snippet taken from 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 toIteratoreither toStreamon erto get true Iteratoror Stream.

And here is version 2.7, which is slightly different. However, testing does seem to indicate that it does not detect the end of the stream, unlike 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)
  }
}
+24
source
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 ...

-2
source

Source: https://habr.com/ru/post/1747551/


All Articles