确定 Nokogiri 元素的子索引

发布于 2024-12-19 07:40:38 字数 708 浏览 3 评论 0原文

如果我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

痴梦一场 2024-12-26 07:40:38

怎么样:

element.parent.children.index(element)

仅考虑非文本节点:

element.xpath('../*').index(element)

仅考虑条形节点:

element.xpath('../bar').index(element)

How about:

element.parent.children.index(element)

To consider only non-text nodes:

element.xpath('../*').index(element)

To consider only bar nodes:

element.xpath('../bar').index(element)
Bonjour°[大白 2024-12-26 07:40:38

技术 1:找到我的兄弟姐妹,看看我在他们中的位置:

idx = element.parent.element_children.index(element)

# Alternatively:
idx = element.parent.xpath('*').index(element)

技术 2:计算我面前的元素(非文本)节点的数量:

idx = element.xpath('count(preceding-sibling::*)').to_i

# Alternatively, if you want to waste time and memory:
# idx = element.xpath('preceding-sibling::*').length

技术 2 明显更快。

Technique 1: Find my siblings, see where I fit within them:

idx = element.parent.element_children.index(element)

# Alternatively:
idx = element.parent.xpath('*').index(element)

Technique 2: Count the number of element (not text) nodes before me:

idx = element.xpath('count(preceding-sibling::*)').to_i

# Alternatively, if you want to waste time and memory:
# idx = element.xpath('preceding-sibling::*').length

Technique 2 is measurably faster.

时间海 2024-12-26 07:40:38

这将选择具有相同元素名称的节点并返回索引:


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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文