3

For a XML snippet like this:

val fruits = <fruits> <fruit> <name>apple</name> <taste>red</taste> </fruit> <fruit> <name>banana</name> <taste>yellow</taste> </fruit> <fruit> <name>banana</name> <taste>green</taste> </fruit> <fruit> <name>apple</name> <taste>green</taste> </fruit> </fruits> 

doing something like:

fruits \\ "fruit" 

will return a sequence of type scala.xml.NodeSeq with all the fruits and sub nodes inside.

How can I limit this sequence to contain only the fruit elements with 'banana' inside. ie, I want the result to be:

<fruits> <fruit> <name>banana</name> <taste>yellow</taste> </fruit> <fruit> <name>banana</name> <taste>green</taste> </fruit> <fruits> 
1
  • the <fruit> tags in your expected output don't match up. Commented Apr 13, 2012 at 14:45

1 Answer 1

4
(fruits \\ "fruit").filter(x => // filter the sequence of fruits (x \\ "name") // find name nodes .flatMap(_.child.map(_.text)) // get all name node text values .contains("banana")) // see which name nodes contain "banana" 

Returns the NodeSeq:

 <fruit> <name>banana</name> <taste>yellow</taste> </fruit> <fruit> <name>banana</name> <taste>green</taste> </fruit> 
Sign up to request clarification or add additional context in comments.

3 Comments

I would use equals instead of contains but otherwise this solution is perfect.
@ChrisJamesC, the flatMap returns a List[String] in case there are multiple <name> nodes. So contains makes sure that at least one of them says "banana".
My bad, now I understand. Thanks for the precision.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.