Find the maximum child count with XPath 1.0

前端 未结 3 1182
谎友^
谎友^ 2021-01-23 06:27

Can I find one XML node with the most children with XPath?


  
    
  
  
    <         


        
相关标签:
3条回答
  • 2021-01-23 07:00

    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

    0 讨论(0)
  • 2021-01-23 07:03

    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 nodes, 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 nodes 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.

    0 讨论(0)
  • 2021-01-23 07:20

    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.

    0 讨论(0)
提交回复
热议问题