查找DomNode/Xpath子元素的索引位置 [英] Find index position of a DomNode/Xpath Child Element
问题描述
我正在使用xpath表达式来确定DOM树中的某个div类(感谢VolkerK!).
I am using an xpath expression to determine a certain div-class in my DOM tree (thanks to 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().
Eventually I need to know which (global) index position my child 'foo' has, because I want to replace it with jQuery later: eq() or nth-child().
有办法吗?
I am following up on another Question of mine about selecting the right element (XPath/Domdocument check for child by class name).
谢谢!
更新:
UPDATE:
我发现使用:
$html['node-position'] = $node->getNodePath()
实际上以父节点的xpath语法(/html/body/div [3])给出了路径和元素编号,但是如何为子div'foo'提供路径和元素编号?
actually gives me the path and the element number in xpath syntax (/html/body/div[3]) of the parent node, but how can it for the child div 'foo'?
推荐答案
用于查找给定元素x
的位置"的XPath方法(其中,位置被定义为表示索引的索引) XML文档中所有x
元素的顺序(按文档顺序)中的元素x
是:
The XPath way to find the "position" of a given element x
(where position is defined to mean the index of that element x
in the sequence (in document order) of all x
elements in the XML document) is:
count(preceding::x) + count(ancestor-or-self::x)
当此XPath表达式以元素x
作为当前节点(初始上下文节点)进行求值时,将产生如此定义的位置".
When this XPath expression is evaluating with the element x
as the current node (initial context node), the so defined "position" is produced.
基于XSLT的验证:
让我们拥有这个XML文档:
Let's have this XML document:
<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>
使用文档中的第3个emp
元素作为初始上下文节点,计算以上XPath表达式.表达式中的x
现在已替换为我们想要的元素名称-emp
.然后输出表达式求值的结果-我们看到这是想要的正确结果:
evaluates the above XPath expression using the 3rd emp
element in the document as the initial context node. The x
in the expression is now substituted by our wanted element name -- emp
. Then the result from the expression evaluation is output -- we see that this is the wanted, correct result:
3
这篇关于查找DomNode/Xpath子元素的索引位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!