gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:44:30 26 4
gpt4 key购买 nike

使用 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>

然后我运行一个查询

node = doc.search('//*[contains(@class, "def")]').first

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

<p>Hello</p>
<most_inner>Howdy</most_inner>

最佳答案

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

# 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

关于ruby - 在 Nokogiri 中,如何找到文档中某个节点之前的所有节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43218476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com