Firstly control enters into first "WHILE" loop, do the processing based upon MAIN_QUERY and once it enters into second "WHILE" loop, it doing the processing for all the child nodes (childproduct1.1, childproduct1.2, childproduct2.1, childproduct2.2)
But I want it to process it only for (childproduct1.1, childproduct1.2) and when the second time it comes then do the processing for (childproduct2.1, childproduct2.2)
I have tried many options but not able to achieve this. Can anyone suggest some options please.
Is there any option to append xPath queries?
private static final String MAIN_QUERY = "/jcr:root/content/data/myproject/products//*[@sling:resourceType='myproject/common/components/template1']";
private static final String SUB_QUERY = "/jcr:root/content/data/myproject/products//*[@sling:resourceType='myproject/common/components/template2']";
private static final String SUB_QUERY = MAIN_QUERY + //*[@sling:resourceType='myproject/common/components/template2']";
You are getting all the child nodes (childproduct1.1, childproduct1.2, childproduct2.1, childproduct2.2) because of the path under which the query is being executed. Since all of these fall under the path "/jcr:root/content/data/myproject/products" it fetches all resources with sling:resourceType='myproject/common/components/template2.
For the desired result you would need to first make the two while loops nested. Results from MAIN_QUERY would form the outer while loop and the ones we get from SUB_QUERY would be inner while loop. SUB_QUERY now will not be static and final as a part of it representing the search path has to be updated in each iteration.
When you get the resource in each iteration of the outer while loop then the resource's path is to be assigned to String variable SUB_QUERY along with the resourcetype property value as xpath query. Each iteration of the outer while loop gets us the resource under which the SUB_QUERY is to be executed.
With the execution of SUB_QUERY updated in each outer iteration we get the iterator to the required resources(with sling:resourceType = myproject/common/components/template2) which fall under the resource we get in the iteration of outer while loop.
In this way we would get the resources(with sling:resourceType = myproject/common/compo nents/template2) under each mainproduct node in different iterations of outer while loop.