在Nokogiri中,如何找到文档中某个节点之前的所有节点?

Dav*_*ave 11 ruby parsing nokogiri ruby-on-rails-5

使用Rails 5,Ruby 2.4.如果我使用Nokogiri解析找到了一个节点,我怎样才能找到在找到的节点之前发生的所有节点,这些节点还没有包含找到的节点?也就是说,让我说我的文件是

<outer>
    <p>Hello</p>
    <inner>
        <most_inner class="abc">Howdy</most_inner>
        <most_inner class="def">Next</most_inner>
    </inner>
</outer>
Run Code Online (Sandbox Code Playgroud)

我运行一个类似的查询

node = doc.search('//*[contains(@class, "def")]').first
Run Code Online (Sandbox Code Playgroud)

我如何找到所有前面的节点(不包括我刚刚确定的节点)?我期望的节点将是

<p>Hello</p>
<most_inner>Howdy</most_inner>
Run Code Online (Sandbox Code Playgroud)

fny*_*fny 5

您只需要遍历叶节点,直到到达目标节点。

# Node to exclude
node = doc.search('//*[contains(@class, "def")]').first
preceding_nodes = []

# Find all leaf nodes
leaf_nodes = doc.xpath("//*[not(child::*)]")

leaf_nodes.each do |leaf|
  if leaf == node
    break
  else
    preceding_nodes.push(leaf)
  end
end

preceding_nodes # => Contains all preceding leaf nodes
Run Code Online (Sandbox Code Playgroud)