1

我正在使用 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 check for child by class name)。

谢谢!

更新:

我发现使用:

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

实际上给了我父节点的xpath语法(/html/body/div[3])的路径和元素编号,但是对于子div'foo'怎么办?

4

2 回答 2

4

查找给定元素的“位置”的 XPath 方法x(其中位置定义为表示该元素在 XML 文档x中所有元素的序列(按文档顺序)中的索引)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
于 2012-02-27T18:05:15.427 回答
0

Foreach支持syntax $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;
}
于 2012-02-27T12:46:48.517 回答