我正在尝试构建一个Sanitize转换器,它可以接受带有任何标记之外的元素的潜在格式错误的HTML输入,如下例所示:
out of a tag<p>in a tag</p>out again!我想让转换器将任何未标记的元素包装在<p>标记中,以便上面的代码转换为:
<p>out of a tag</p><p>in a tag</p><p>out again!</p>不幸的是,我不知道如何选择未标记的元素,因为它不是一个节点。我肯定我漏掉了什么。有人能给我一个正确的方向吗?
发布于 2010-07-03 01:51:33
require 'nokogiri'
html = 'out of a tag<p>in a tag</p>out again!'
Nokogiri::HTML(html).at_css('body').children.
map {|x| '<p>' + x.text + '</p>' }.join('')
#=> "<p>out of a tag</p><p>in a tag</p><p>out again!</p>"文本存储在文本节点中。因为CSS不能选择文本节点,所以您必须使用其他方法来获取它们,比如Nokogiri::XML::Node#children。
https://stackoverflow.com/questions/3167809
复制相似问题