确定 Nokogiri 元素的子索引

3
如果我有一个 Nokogiri::XML::Element,如何确定它在父元素中的子级索引?也就是说:
<foo>     <-- parent
  <bar/>  <-- 1st child
  <bar/>  <-- 2nd child
</foo>

在Javascript世界中,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
3个回答

7
如何考虑:
element.parent.children.index(element)

仅考虑非文本节点:

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

只考虑柱状节点:

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

1
请注意,此操作将包括列表中的文本节点。 - Phrogz
太好了!@Phrogz,我明白了,但是可以通过使用element_children(就像您的答案中一样)轻松解决这个问题。 - lambshaanxy

3
技巧一:找到我的兄弟姐妹,看看我在其中的位置。
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

技巧二明显更快。


1
这会选择相同元素名称的节点并返回索引:

element.parent.xpath(element.name).index(element)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接