John Wickerson
John Wickerson

Reputation: 1232

get value of XML node, ignoring its children's values

I have an XML file that looks like this

<a>
  hello
  <b>
    world
  </b>
</a>

I would like to use Scala to extract just a's value, without including any of its children (i.e. without including b's value). Currently, if a is a scala.xml.Node, then a.text returns helloworld. What do I type if I just want hello?

Upvotes: 0

Views: 79

Answers (1)

Hugh
Hugh

Reputation: 8932

Both the text node hello and the element node <b>world</b> are children of a. If you want to get just the text nodes, you can use the normal collection methods:

val x = <a>Hello<b>world</b></a>
x.child.collect {
  case t: xml.Text ⇒ t.toString
}.mkString // "hello"

Upvotes: 2

Related Questions