查找DomNode/Xpath子元素的索引位置


Find index position of a DomNode/Xpath Child Element

我正在使用xpath表达式来确定DOM树中的某个div类(感谢VolkerK!)。

foreach($xpath->query('//div[@class="posts" and div[@class="foo"]]') as $node)
    $html['content'] = $node->textContent;
    //$html['node-position'] = $node->position(); // (global) index position of the child 'foo'
}

最后,我需要知道我的孩子"foo"有哪个(全局)索引位置,因为我想稍后用jQuery替换它:eq()或nth-child()。

有办法做到吗?

我正在跟进我的另一个关于选择正确元素的问题(XPath/Domdocument按类名检查子元素)。

谢谢!

更新:

我发现使用:

$html['node-position'] = $node->getNodePath() 

实际上,在xpath语法(/html/body/div[3])中给了我父节点的路径和元素编号,但它怎么能用于子节点div"foo"呢?

查找给定元素x的"位置"的XPath方法(其中位置被定义为表示该元素x在XML文档中所有x元素的序列(按文档顺序)中的索引)

count(preceding::x) + count(ancestor-or-self::x)

当这个XPath表达式以元素x作为当前节点(初始上下文节点)进行计算时,就会产生这样定义的"位置"。

基于XSLT的验证

让我们有一个XML文档:

<t>
    <d/>
    <emp/>
    <d>
        <emp/>
        <emp/>
        <emp/>
    </d>
    <d/>
</t>

此转换

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:variable name="v3rdEmp" select="/*/d/emp[2]"/>
 <xsl:template match="/">
  <xsl:value-of select=
   "count($v3rdEmp/preceding::emp)
   +
    count($v3rdEmp/ancestor-or-self::emp) "/>
 </xsl:template>
</xsl:stylesheet>

使用文档中的第三个emp元素作为初始上下文节点来评估上述XPath表达式。表达式中的x现在被我们想要的元素名称——emp所取代。然后输出表达式求值的结果——我们看到这是想要的、正确的结果:

3

Foreach支持语法$traversable as $key => $item,因此当您使用:时

foreach($xpath->query('//div[@class="posts" and div[@class="foo"]]') as $key => $node)
    $html['content'] = $node->textContent;
    $html['node-position'] = $key;
}