我正在寻找有关如何完成操作的建议。我正在尝试仅使用xpath的解决方案:
一个html示例:
<div>
<div>
<div>text div (leaf)</div>
<p>text paragraph (leaf)</p>
</div>
</div>
<p>text paragraph 2 (leaf)</p>
代码:
doc = Nokogiri::HTML.fragment("- the html above -")
result = doc.xpath("*[not(child::*)]")
[#<Nokogiri::XML::Element:0x3febf50f9328 name="p" children=[#<Nokogiri::XML::Text:0x3febf519b718 "text paragraph 2 (leaf)">]>]
但是这个xpath只给我最后一个“ p”。我想要的是一个扁平行为,只返回叶节点。
以下是stackoverflow中的一些参考答案:
谢谢
您的代码存在以下问题:
doc = Nokogiri::HTML.fragment("- the html above -")
看这里:
require 'nokogiri'
html = <<END_OF_HTML
<div>
<div>
<div>text div (leaf)</div>
<p>text paragraph (leaf)</p>
</div>
</div>
<p>text paragraph 2 (leaf)</p>
END_OF_HTML
doc = Nokogiri::HTML(html)
#doc = Nokogiri::HTML.fragment(html)
results = doc.xpath("//*[not(child::*)]")
results.each {|result| puts result}
--output:--
<div>text div (leaf)</div>
<p>text paragraph (leaf)</p>
<p>text paragraph 2 (leaf)</p>
如果我运行此命令:
doc = Nokogiri::HTML.fragment(html)
results = doc.xpath("//*[not(child::*)]")
results.each {|result| puts result}
我没有输出。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句