Created
September 17, 2009 20:02
-
-
Save luikore/188676 to your computer and use it in GitHub Desktop.
scala RichNodeSeq
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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