Search code examples
xmlscalachildren

Scala: get child nodes count in XML


I've XML in the format

val XML = 
<a>
 <b>value_b</b>
 <c>
   <c_1>value_c_1</c_1>
   <c_2>value_c_2</c_2>
   <c_3>value_c_3</c_3>
 </c>
 <b>value_b</b>
 <c>
   <c_1>value_c_1</c_1>
   <c_2>value_c_2</c_2>
   <c_3>value_c_3</c_3>
 </c>
 <b>value_b</b>
 <c>
   <c_1>value_c_1</c_1>
   <c_2>value_c_2</c_2>
   <c_3>value_c_3</c_3>
 </c>
</a>

I want to get the count for the children under <c> I tried (XML \\ "c").length

But this gives the count for all <c> tags. I can't access descendant as (XML \\ "c") returns NodeSeq

Trying (XML \\ "c" \\ "_").length gives total length of all records. Not sure how I can access the child nodes. Any ideas?

EDIT: (XML \\ "c" \ "_").length / (XML \\ "c").length this gives correct count of fields under <c>. But, I feel it a bit clumsy. A nicer solution is needed.


Solution

  • (XML \\ "c" \ "_").length gives 9 (Count of all "c" children)

    ((XML \ "c")(0) \ "_").length gives 3 (Count of first "c" children)