Stupid.Fat.Cat
Stupid.Fat.Cat

Reputation: 11285

Scala: Iterating through an xml Node

There is no problem iterating through this:

<entries>
    <entry>
    <name>Kitten</name>
    <special>Yup</special>
    </entry>
    <entry>
    <name>Gato</name>
    <special>Nope</special>
    </entry>
</entries>

with this approach

for(entry <- data)
...

But now when I try to iterate within an entry

ie:

<entry>
<name>Kitten</name>
<special>Yup</special>
</entry>

I can't actually go through name and then proceed to special instead, it just treats this Node as one item and only goes through one cycle. How do I go through each and every element?

Upvotes: 2

Views: 2646

Answers (2)

cmbaxter
cmbaxter

Reputation: 35443

If you want a list of child elements from the root, regardless of depth, then you can do this:

val elems = xml.descendant.collect{case e:Elem => e}

The resulting elems will be a List[Elem] representing any child Elem from the root.

Upvotes: 3

ArtemGr
ArtemGr

Reputation: 12547

With a child method, perhaps?

For example,

for (bar <- <foo><bar><kv/></bar><bar><kv/></bar></foo>.child; kv <- bar.child) {println (kv)}

prints

<kv/>
<kv/>

Upvotes: 3

Related Questions