Can I find one XML node with the most children with XPath?
<
I think that it is impossible because to count children you need function count()
which has one parameter - node-set and returns count of elements in this set. So you have no option how to count more node-sets than one to get max value.
Note: I am talking about XPath 1.0
I also don't think this is possible (based on the fact that I haven't been able to do it :)). Of course, if you're allowed to change the xml (even just temporarily during this processing), you could update it to put the child count as an attribute on the node (or as the node value itself), after which it's easy:
/xml/node[not(../node/@childCount > ./@childCount)]
or
/xml/node[not(../node > .)]
But you probably already know that.
The other thing I thought might work was to do some clever maths along pigeon-hole principle lines, to take as inputs the total child count and the number of node
s, and produce a minimum child count that the max-node must have, and then doing
/xml/node[child[position()=formula_for_magic_number_goes_here]]
but I soon realised that I couldn't come up with such a formula that would correctly deal with all cases - for example, if there were 10 node
s with child counts of 10, 99 1, 1, (and the rest 1s too), no amount of manipulation of the numbers 27 and 10 is going to produce a cut off point that includes 10 but excludes 9.
I know this is pretty old, but if it helps anyone out, I wanted to do this and I think this works, at least it does for me:
/xml/node[count(./child) > count(following-sibling::node/child) and count(./child) > count(preceding-sibling::node/child)]
I'm not great with Xpath so maybe I'm missing something.