Parsing XML in Scala does not seem as simple and straightforward as it should be.
I needed something that looked like a document.getElementsByTagName (name) in JavaScript, but for my purposes, all I needed was the first element of a specific tag name. Here is what I ended up with:
import scala.xml.{Document, Elem, Node} import scala.xml.parsing.ConstructingParser def _getFirstMatchingElementByName(search: String, n: Node): Option[Node] = { if (n.label == search) { Some(n) } else { var i = 0 var result: Option[Node] = None try { while (result == None) { result = _getFirstMatchingElementByName(search, n.child(i)) i += 1 } } catch { case e: IndexOutOfBoundsException => None } result } }
It is mainly repeated until a match is found or all possibilities are exhausted.
Now that a feature that requires me to have this ability has been released. I looked at it a little more and it really hurts me. I'm sure there are many Java libraries available that help parsing XML, but given the built-in support that Scala has for generating XML (i.e., it can just be embedded anywhere), I'm curious if I missed something .
Is there a better way to do this in Scala?
source share