gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:06:17 25 4
gpt4 key购买 nike

我正在使用 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'
}

最终我需要知道我的 child 'foo' 有哪个(全局)索引位置,因为我想稍后用 jQuery 替换它: eq()或第 n 个 child ()。

有没有办法做到这一点?

我正在跟进我的另一个关于选择正确元素的问题( XPath/Domdocument check for child by class name)。

谢谢!

更新:

我发现使用:
$html['node-position'] = $node->getNodePath() 

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

最佳答案

查找给定元素“位置”的 XPath 方法 x (其中位置定义为表示该元素的索引 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

关于php - 查找 DomNode/Xpath 子元素的索引位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9465095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com