How to parse xml into "messages" and print them in scala using flow analysis?

Now that I know how to parse xml in scala as a stream, I need help understanding a non-trivial example.

I would like to parse the following xml as a stream and send a message (print to the console for this example) whenever I parse the full message.

I understand that scala thread-based parsing uses case classes to handle different elements, but I'm just getting started, and I don't quite understand how to do this.

This works for me in java using the stax parser, and I'm trying to translate it into scala.

Any help would be greatly appreciated.

<?xml version="1.0" ?>
<messages>
<message>
   <to>john.doe@gmail.com</to>
   <from>jane.doe@gmail.com</from>
   <subject>Hi Nice</subject>
   <body>Hello this is a truly nice message!</body>
</message>
<message>
   <to>joe@gmail.com</to>
   <from>jane.doe@gmail.com</from>
   <subject>Hi Nice</subject>
   <body>Hello this is a truly nice message!</body>
</message>
</messages>
+3
1

2.8.

. (, , ):

import scala.xml.pull._
import scala.io.Source
import scala.collection.mutable.Stack

val src = Source.fromString(xml)
val er = new XMLEventReader(src)
val stack = Stack[XMLEvent]()
def iprintln(s:String) = println((" " * stack.size) + s.trim)
while (er.hasNext) {
  er.next match {
    case x @ EvElemStart(_, label, _, _) =>
      stack push x
      iprintln("got <" + label + " ...>")
    case EvElemEnd(_, label) => 
      iprintln("got </" + label + ">")
      stack pop;
    case EvText(text) => 
      iprintln(text) 
    case EvEntityRef(entity) => 
      iprintln(entity) 
    case _ => // ignore everything else
  }
}

- , , , .

, EvElemStart(pre, label, attrs, scope) , if .

, 2.7.x, , http://lampsvn.epfl.ch/trac/scala/ticket/2583, .

, ( Scala):

class Message() {
  var to:String = _
  var from:String = _
  override def toString(): String = 
    "from %s to %s".format(from, to)
}

var message:Message = _
var sb:StringBuilder = _

while (er.hasNext) {
  er.next match {
    case x @ EvElemStart(_, "message", _, _) =>
      message = new Message
    case x @ EvElemStart(_, label, _, _) if
        List("to", "from") contains label =>
      sb = new StringBuilder 
    case EvElemEnd(_, "to") => 
      message.to = sb.toString
    case EvElemEnd(_, "from") => 
      message.from = sb.toString
      sb = new StringBuilder 
    case EvElemEnd(_, "message") => 
      println(message)
    case EvText(text) if sb != null => 
      sb ++= text
    case EvEntityRef(entity) => 
      sb ++= unquote(entity) // todo
    case _ => // ignore everything else
  }
}
+4

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


All Articles