确定 Nokogiri 元素的子索引
如果我有一个 Nokogiri::XML::Element,我如何计算其子索引相对于其父索引的关系?也就是说:
<foo> <-- parent
<bar/> <-- 1st child
<bar/> <-- 2nd child
</foo>
在 Javascriptland 中,jQuery 有 index(),但 Nokogiri 没有。 Nokogiri 确实提供了 path 方法,但返回一个 XPath 字符串就像 "/foo/bar[2]"
并将 bar[1]
截断为 bar
来引导,因此将其转回数字是有点毛:
element.path.split('/').last.slice(/[0-9]+/) || '1' # quick'n'dirty
element.path.split('/').last.slice(/\[([0-9]+)\]/, 1) || '1' # a bit safer
if I have a Nokogiri::XML::Element, how do I figure its child index in relation to its parent? That is:
<foo> <-- parent
<bar/> <-- 1st child
<bar/> <-- 2nd child
</foo>
In Javascriptland, jQuery has index(), but Nokogiri doesn't. Nokogiri does provide a path method, but that returns an XPath string like "/foo/bar[2]"
and truncates bar[1]
to bar
to boot, so turning that back into a number is a little hairy:
element.path.split('/').last.slice(/[0-9]+/) || '1' # quick'n'dirty
element.path.split('/').last.slice(/\[([0-9]+)\]/, 1) || '1' # a bit safer
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
怎么样:
仅考虑非文本节点:
仅考虑条形节点:
How about:
To consider only non-text nodes:
To consider only bar nodes:
技术 1:找到我的兄弟姐妹,看看我在他们中的位置:
技术 2:计算我面前的元素(非文本)节点的数量:
技术 2 明显更快。
Technique 1: Find my siblings, see where I fit within them:
Technique 2: Count the number of element (not text) nodes before me:
Technique 2 is measurably faster.
这将选择具有相同元素名称的节点并返回索引:
element.parent.xpath(element.name).index(element)
This selects nodes of the same element name and returns the index:
element.parent.xpath(element.name).index(element)