//X 和 /descendant::X 之间的唯一区别是当 X 包含一个位置谓词,例如 //x[1] 与 /descendant::x[1].在这种情况下,//x[1] 选择作为其父元素的第一个 x 子元素的每个 x 元素,而 /后代::x[1] 选择第一个后代 x 整体.你可以通过记住 //x[1] 是 /descendant-or-self::node()/child::x[1] 的缩写来解决这个问题
I can't clearly understand the differences between using //element and /descendant::element when selecting multiple children of a base element in XPath.
I need to select each input based on its positioning in the table.//div[@class='popupContent']//input[1] this selects the first input//div[@class='popupContent']//input[2] this gives error//div[@class='popupContent']/descendant::input[1] this again selects the first input//div[@class='popupContent']/descendant::input[2] this select the second input
Using /descendant::input does what I need: grab all inputs and let me select by position. How does // differ? Why does it return only the first element and not the ones after?
I'm aware of this other question but the answer basically says they're aliases and point to the documentation, which I cannot understand and lacks a concrete example. Difference with that question is that my need is to select multiple children elements, and // doesn't allow it.
解决方案
The only difference between //X and /descendant::X is when X contains a positional predicate, for example //x[1] vs /descendant::x[1]. In this situation //x[1] selects every x element that is the first x child of its parent element, whereas /descendant::x[1] selects the first descendant x overall. You can work this out by remembering that //x[1] is short for /descendant-or-self::node()/child::x[1]