Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is for 2.8.</p> <p>The typical way to process events is to use a match statement. In my case, i always had the need to store the parents as I process elements (to know for instance in what tag the text is located):</p> <pre><code>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, _, _) =&gt; stack push x iprintln("got &lt;" + label + " ...&gt;") case EvElemEnd(_, label) =&gt; iprintln("got &lt;/" + label + "&gt;") stack pop; case EvText(text) =&gt; iprintln(text) case EvEntityRef(entity) =&gt; iprintln(entity) case _ =&gt; // ignore everything else } } </code></pre> <p>Because entity are events, you will probably need to convert to text and combine them with the surrounding text. </p> <p>In the example above I only used label, but you can also use <code>EvElemStart(pre, label, attrs, scope)</code> to extract more stuff and you can add an <code>if</code> guard to match for complex conditions.</p> <p><em>Also if you're using 2.7.x, I don't know if <a href="http://lampsvn.epfl.ch/trac/scala/ticket/2583" rel="noreferrer">http://lampsvn.epfl.ch/trac/scala/ticket/2583</a> was back-ported so, you may have issues to process text with entities.</em></p> <p>More to the point, just dealing with from and to for brevity (though I would not call that the <em>Scala way</em>):</p> <pre><code>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", _, _) =&gt; message = new Message case x @ EvElemStart(_, label, _, _) if List("to", "from") contains label =&gt; sb = new StringBuilder case EvElemEnd(_, "to") =&gt; message.to = sb.toString case EvElemEnd(_, "from") =&gt; message.from = sb.toString sb = new StringBuilder case EvElemEnd(_, "message") =&gt; println(message) case EvText(text) if sb != null =&gt; sb ++= text case EvEntityRef(entity) =&gt; sb ++= unquote(entity) // todo case _ =&gt; // ignore everything else } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload