gpt4 book ai didi

ruby - 在两个节点之间获取 xpath 的最简单方法

转载 作者:太空宇宙 更新时间:2023-11-03 16:02:16 25 4
gpt4 key购买 nike

使用 nokogiri,只需调用 node.path 即可轻松获得从任何节点返回到根的绝对路径。举个例子:

<bookstore>
<department category="COOKING">
<book>
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book>
<title lang="en">Nice meals</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</department>
<department category="WEB">
<book>
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</department>
</bookstore>

如果我这样做

tree.search("//title[text() = 'Learning XML']").first.path

我会得到类似bookstore/department[2]/book[1]/title[1]

现在,如果我想获取此节点的路径,而不是从根节点获取,我想从例如//department[@category='WEB'] 一直到同一个标题节点?

换句话说。我一般如何获取/生成两个已知节点之间的路径,例如 //department[@category='WEB']bookstore/department[2]/book[1]/title[ 1]?

编辑

我一直在考虑将 //department[@category='WEB'] 变成一种新的“根”的方法,例如通过删除一些东西,然后再次在标题节点上使用 .path 方法。这似乎不是很“简单”...

最佳答案

我对最后基于字符串的 hack 并不感兴趣,但现在这会产生干净的 XPaths:

require 'nokogiri'
class Nokogiri::XML::Node
def path_to( node )
self_ancestors = [self].concat(self.ancestors)
shared = (self_ancestors & [node].concat(node.ancestors)).first
[ "../"*self_ancestors.index(shared),
".", node.path[shared.path.length..-1] ]
.join
.sub( %r{\A\./|/\.(?=/|\z)}, '' ) # remove superfluous "."
end
end

doc = Nokogiri.XML(IO.read('tmp.rxml'))
n1 = doc.at("//department[@category='WEB']")
n2 = doc.at("//title[.='Learning XML']")
n3 = doc.at("//year[.='2003']")
n4 = doc.at("//@lang")

p n1.path_to(n2) #=> "book/title"
p n2.path_to(n3) #=> "../year"
p n3.path_to(n2) #=> "../title"
p n2.path_to(n1) #=> "../.."
p n1.path_to(n1) #=> "."
p n4.path_to(n2) #=> "../../../../department[2]/book/title"
p n2.path_to(n4) #=> "../../../department[1]/book[1]/title/@lang"

p n2.at( n2.path_to(n4) )==n4 #=> true

关于ruby - 在两个节点之间获取 xpath 的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21768487/

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