how to get horizontal depth of a node?

2019-06-05 17:40发布

问题:

note i made up the term horizontal depth to measure the sub-dimension of a node within a tree.

so imagine a which would have xpath something like /html/table/tbody/tr/td, and "horizontal depth" of 5

i am trying to see if there is a way to identify and select elements based on this horizontal depth.

how can i find the maximum depth ?

回答1:

If you need all the nodes with depth >= 5:

/*/*/*/*//*

And if you need all the nodes with depth == 5:

/*/*/*/*/*

Actually, there is a XPath function count, which you can combine with ancestor axis:

//*[count(ancestor::*) >= 4]


回答2:

I think that "vertical depth" and "horizontal depth" are ambiguous. Is there any reason not to use the axis terminology that already exists in XPath, and refer to "number of ancestors" and "number of preceding siblings"? It's slightly more verbose, but not much, and a) it's unambiguous and b) the terms map onto count(ancestor::*) and count(preceding-sibling::*).