如何使用Nokogiri用<p>标签包装HTML无标记文本?</p>

时间:2012-01-20 07:01:02

标签: html ruby xml nokogiri

我必须将HTML文档解析为不同的新文件。问题是有些文本节点没有用"<p>"个标签包装,而是在每个段落的末尾都有"<br>"个标签。

我想使用Nokogiri用<p>标签包装此文本:

<div id="f15"><b>Footnote 15</b>: Catullus iii, 12.</div>
<div class="pgmonospaced pgheader"><br/>
<br/>
End of the Project abc<br/>
<br/>
*** END OF THIS PROJECT XYZ ***<br/>
<br/>
***** This file should be named new file.html... *****<br/>
<br/></div>

1 个答案:

答案 0 :(得分:5)

在搜索一些论坛并在本地进行一些调试之后,我找到了以下解决方案来解决我的问题。

html_doc = Nokogiri::HTML.parse('path/to/html_file')
html_doc
html_doc.search("//br/preceding-sibling::text()|//br/following-sibling::text()").each do |node|
    node.replace(Nokogiri.make("<p>#{node.to_html}</p>"))
end