0

I want to get the count of xml nodes present in the file with specific tags in camel exchange or camel route.

My xml tags are like this:

<parent>
  <child>
    <data>A</data>
  </child>
  <child>
    <data>B</data>
  </child>
  <child>
    <data>C</data>
    <child>
       <data>C1</data>
    </child>
    <child>
       <data>C2</data>
    </child>
  </child>
</parent>

I want to count the <child> tags and it should return 5 for this.

Currently, I am getting size using Exchange but it is giving output as 3.

exchange.getIn().getBody(XmlTreesType.class).getParentTree().getChildNode().size(); 
  • You can also count the number `` text's in the xml as a string value. Or try to use xpath and a count function – Claus Ibsen Sep 26 '19 at 14:22
  • Hi claus, I am very much fresher in camel and not sure about many things. Help me out with a bit of example to get the count. Help will be appreciated – Gagan Noor Singh Sep 27 '19 at 06:01

1 Answers1

2

This highly depends on your actual use case.

To extract the count, you could use the XPath language which allows you to extract information from XML easily.

To extract the count of all <child> nodes within your <parent> you could use the following:

count(/parent//child)

XPath expression.

To extract this value and store it in a header variable would look like this:

.from()
  .setHeader("childCountHeader", xpath("count(/parent//child)", Integer.class));

Another typical use case in the camel Java DSL would be along the following, in order to directly route based on the count:

from()
  .choice().xpath("count(/parent//child)>5")
  //do something
  .otherwise()
  //do something else
  .end();

If you want to use XPath inside vanilla java, as in a camel processor. You can build up an XPath processor as described in this answer.

Daniel
  • 3,541
  • 3
  • 33
  • 46