我正在寻找一些关于如何完成的建议。我想一个解决方案只使用XPath:如何仅选择Nokogiri的叶节点?
一个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”。我想要的就像一个平坦的行为,只返回叶节点。
下面是计算器一些参考答案:
How to select all leaf nodes using XPath expression?
XPath - Get node with no child of specific type
感谢
你想要什么值? –
文本上有(叶)的所有节点 – Luccas
@Luccas:你只想要文本,还是你想要包含元素?即你想'文本段落(叶)'还是'
文本段落(叶)
'?如果你只想要文本,你想单独使用所有的文本节点,还是只需要将所有文本作为单个字符串进行拼接? – Borodin