Reputation: 4240
I'm trying to parse XML in Scala using scala.xml.XML and I would like to avoid having to pass strings via XPath to an XML Elem in order to get a NodeSeq.
Having to specify strings like elem \\ "tag1" \\ "tag2" \\ "@tagN"
in multiple places seems fragile and repetitive.
Most of the Scala XML parsing tutorials have you parsing with XPath hardcoded string jank - elem \\ "tag1" \\ "tag2" \\ "@tagN"
- everywhere.
Is it possible to write a method that takes a searches an Elem through a Seq[String] via XPath and returns a NodeSeq?
The method would look something like:
def getNodeFromXml(elem: Elem, tags: Seq[String]): NodeSeq = {
Returns a NodeSeq elem \\ tags(0) \\ tags(1) \\ ... \\ tags(tags.length)
}
Thanks
Upvotes: 2
Views: 1105
Reputation: 39577
Something like:
scala> import xml._
import xml._
scala> val x = <top><middle><bottom>text</bottom></middle></top>
x: scala.xml.Elem = <top><middle><bottom>text</bottom></middle></top>
scala> val names = Seq("middle","bottom")
names: Seq[String] = List(middle, bottom)
scala> val ns: NodeSeq = x
ns: scala.xml.NodeSeq = <top><middle><bottom>text</bottom></middle></top>
scala> names.foldLeft(ns)((e,s) => e \\ s)
res2: scala.xml.NodeSeq = NodeSeq(<bottom>text</bottom>)
Upvotes: 2