2

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

1 Answer 1

2

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>)
Sign up to request clarification or add additional context in comments.

1 Comment

This is much cleaner than the approach I was trying. I was trying to use recursion passing the NodeSeq + tail of the Seq down and when seq.length was 1, returning the final NodeSeq. I was trying to use collection built-ins for this but never thought to use foldLeft. Thank you for sharing!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.