joesan
joesan

Reputation: 15345

Scala XML fetch a value based on tag name

Is it possible to get the value of a tag based on the tags name? For example., in the following xml,

<root>
  <a>
    <b>one</b>
    <c>two</c>
  </a>
  <a>
    <b>two</b>
    <c>one</c>
  </a>
</root>

And when I do the following:

val aNodes = root \\ "a"
aNodes.map(aNode => {
  aNode. ??? // How to I get the value of b and c by using its tag name?
})

Upvotes: 0

Views: 122

Answers (1)

yakshaver
yakshaver

Reputation: 2492

You can get the text content of the children elements b and c by navigating to them using the \ path projection function and calling the NodeSeq.text method on the results:

(xml \\ "a") map (e => ((e \ "b") text, (e \ "c") text)) // List((one,two), (two,one))

This returns a Tuple2 containing the values for b and c for all a elements.

Upvotes: 2

Related Questions