Find index position of a DomNode/Xpath Child Element

╄→гoц情女王★ 提交于 2019-12-11 09:23:19

问题


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'
}

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().

Is there a way to do it?

I am following up on another Question of mine about selecting the right element (XPath/Domdocument check for child by class name).

Thanks!

UPDATE:

I have found out that using:

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

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'?


回答1:


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)

When this XPath expression is evaluating with the element x as the current node (initial context node), the so defined "position" is produced.

XSLT - based verification:

Let's have this XML document:

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

This transformation:

<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>

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



回答2:


Foreach supports syntax $traversable as $key => $item, therefore when you use:

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


来源:https://stackoverflow.com/questions/9465095/find-index-position-of-a-domnode-xpath-child-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!