如果我有一个 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
最佳答案
怎么样:
element.parent.children.index(element)
只考虑非文本节点:
element.xpath('../*').index(element)
只考虑条形节点:
element.xpath('../bar').index(element)
关于ruby - 确定 Nokogiri 元素的子索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8381383/