Parsing XML with Scala: equivalent to "getElementByTagName (name)" in JS

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?

+4
source share
1 answer

You are doing it wrong!
all I needed was the first element of a specific tag name
given this xml:

 val page = <root> <need>text1</need> <doesnotneed>text2</doesnotneed> <doesnotneed>text3</doesnotneed> <need>text4</need> </root> 

Now calling this code will give you a list of all nodes with the given tag name:

 scala> page \\ "need" res3: scala.xml.NodeSeq = NodeSeq(<need>text1</need>, <need>text4</need>) 

To get only the first:

 scala> page \\ "need" head res4: scala.xml.Node = <need>text1</need> 

PS An element with a deep first will be considered as a head.

+6
source

All Articles