Extract XML elements with specific child element content using Scala

For an XML fragment 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>

do something like:

fruits \\ "fruit"

returns a sequence of type scala.xml.NodeSeqwith all fruits and sub-nodes inside.

How can I limit this sequence to only contain fruit elements with a โ€œbananaโ€ inside. those. I want the result to be:

<fruits>
  <fruit>
    <name>banana</name>
    <taste>yellow</taste>
  </fruit>
  <fruit>
    <name>banana</name>
    <taste>green</taste>
  </fruit>
<fruits>
+3
source share
1 answer
(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 NodeSeq:

  <fruit>
    <name>banana</name>
    <taste>yellow</taste>
  </fruit>
  <fruit>
    <name>banana</name>
    <taste>green</taste>
  </fruit>
+4
source

All Articles