Given a scala.xml.Node object (with white space and elements as child nodes) what’s the most efficient way of getting the second (or n-th) child element?
Usually I would go for the built-in (node \ "foo"), but sometimes I have to rely on the position of the element. For example, I could have two Choice groups that could be either foo or bar. The document could be
<something>
<foo/>
<foo/>
</something>
or
<something>
<foo/>
<bar/>
</something>
etc.
I like retronym’s
drop(n).headOptionpattern as it accounts for when you have less children thann. But I think you meant the second child node (excluding text nodes), not the second instance of the<foo>tag. With that in mind, combining with your answer or usingpartialMap:This has to assume that you won’t want to extract text in:
Efficiency wise, the only other thing I could think of is to make filter lazy if you wanted to retrieve the second child when there are a large number of children. I think this may be achieved by running filter on
node.child.iteratorinstead.Edit:
Changed
toIterabletoiterator.good point, calling
drop(n)on anArrayBufferwill cause additional allocations, also how many is hard to tell, since it seemsdropis overridden inIndexSeqLike. But using the iterator would address that too. So for large number of children:If you want to have it be safe, you may need to define a function to check for
hasNext.All of this is tested only in 2.8.