Is it possible to store a Scala XML Pattern in a variable? Or at least patterns which search for a particular subtree structure with wildcards? I'd like to load patterns at runtime, e.g.,
import scala.xml._
// Is there something like XMLPattern?
def matchMyPattern(xml: Elem, p: XMLPattern): Option[Seq[Node]] = {
xml match {
case p(save, throwAway) => Some(save)
case _ => None
}
}
val patternsFromFile = Array("<a><b>{ save @ _* }</b>{ throwAway @ _ *}</a>",
"<a>{ throwAway @ _* }<c>{ save @ _* }</c></a>")
val xml = <a><b>x</b><c>y</c></a>
for(pString <- patternsFromFile) {
val p = new XMLPattern(pString)
val extractedSeqNode = matchMyPattern(xml, p)
...
}
I am looking for a way that takes advantage of Scala's great pattern matching abilities. In particular, I would like to avoid:
Writing my own string parsing and subtree search algorithm.
Using a runtime interpreter along the lines of an
Eval(myCode: String).
If it's not possible to access the Scala compiler's internal XML Pattern logic, can the pattern matching be simulated using something like parser combinators for trees?