Can I tell scala.xml to match any of two tags?

183 Views Asked by At

body \\ "div" matches the "div" tags, and body \\ "p" matches the "p" tags.

But what if I'd like to match all the "div" and "p" tags? Is it possible with one expression in scala.xml?

And if not, is there another way to iterate over all the "div" and "p" tags in the document in the order in which they appear?

1

There are 1 best solutions below

3
On BEST ANSWER

If you take a look at the source for \\ in NodeSeq.scala you can see that it's really just a bit of sugar for a filter operation over descendant_or_self, which is a List[Node], using the node's label.

So you could do the same thing yourself, matching against a set of labels, like this:

val searchedLabels = Set("p", "div")

val results = body.descendant_or_self.filter(node => searchedLabels.contains(node.label))

Or if you really want it to seem like "built-in" functionality, you can pimp-on a suitable method to scala.xml.Node like so:

class ExtendedNode(n: Node) {

  def \\\(labels: Set[String]): NodeSeq = {
    n.descendant_or_self.filter(node => labels.contains(node.label))
  }
}

implicit def node2extendedNode(n: Node): ExtendedNode = new ExtendedNode(n)

val results = body \\\ Set("p", "div")

although I must say I'm not sure I like either the method-name or the use of an implicit here :-(