【发布时间】:2013-07-26 20:00:12
【问题描述】:
我正在寻找一些关于如何完成的建议。我正在尝试仅使用 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中的一些参考答案:
How to select all leaf nodes using XPath expression?
XPath - Get node with no child of specific type
谢谢
【问题讨论】:
-
你想要的价值观是什么?
-
文本上带有(叶子)的所有节点
-
@Luccas:你只想要文本,还是想要包含元素?即你想要
text paragraph (leaf)还是<p>text paragraph (leaf)</p>?如果你只想要文本,你想要所有的文本节点分开,还是你只是想要所有的文本连接成一个字符串? -
你的尝试失败的原因是因为你使用了
xpath('*…')而不是xpath('.//*…');见this bug report 和this one。