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

编程入门 行业动态 更新时间:2024-10-25 10:33:37
本文介绍了查找DomNode/Xpath子元素的索引位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用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().

有办法吗?

我正在跟踪我的另一个有关选择正确元素的问题( XPath/Domdocument按类名检查子项).

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="www.w3/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子元素的索引位置

本文发布于:2023-10-08 02:35:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1471263.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:索引   元素   位置   DomNode   Xpath

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!