Skip to content

Instantly share code, notes, and snippets.

@luikore
Created September 17, 2009 20:02
Show Gist options
  • Save luikore/188676 to your computer and use it in GitHub Desktop.
Save luikore/188676 to your computer and use it in GitHub Desktop.
scala RichNodeSeq
// extend scala.xml.NodeSeq to support xpath with attr
// call-seq: ex.RichNodeSeq(<a id="2"/><a/>) \ "a[id=2]"
package ex
import scala.xml._
case class RichNodeSeq(nodeSeq: NodeSeq) extends NodeSeq {
def theSeq = nodeSeq.theSeq
private val attrRe = """^\s*(.*)\s*\[\s*(.*)\s*=\s*(.*)\s*\]$""".r
private def isElemWithAttr(elem: String, attr: String, value: String) =
(node: Node) => (node.label == elem) && (node attribute attr map (_(0) == value) getOrElse false)
override def \ (that: String): NodeSeq = that match {
case attrRe(elem, attr, value) =>
flatMap (_.child) filter isElemWithAttr(elem, attr, value)
case _ => super.\(that) // .()required
}
override def \\ (that: String): NodeSeq = that match {
case attrRe(elem, attr, value) =>
flatMap (_.descendant_or_self) filter isElemWithAttr(elem, attr, value)
case _ => super.\\(that)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment