nokogiri:如何在表格标签之后立即插入 tbody 标签? [英] nokogiri: how to insert tbody tag immediately after table tag?
本文介绍了nokogiri:如何在表格标签之后立即插入 tbody 标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想确保所有表的直接子级都是 tbody ....
i want to make sure all table's immediate child is tbody....
我如何用 xpath 或 nokogiri 写这个?
how can i write this with xpath or nokogiri ?
doc.search("//table/").each do |j|
new_parent = Nokogiri::XML::Node.new('tbody',doc)
j.replace new_parent
new_parent << j
end
推荐答案
require 'rubygems'
require 'nokogiri'
html = Nokogiri::HTML(DATA)
html.xpath('//table').each do |table|
# Remove all existing tbody tags to avoid nesting them.
table.xpath('tbody').each do |existing_tbody|
existing_tbody.swap(existing_tbody.children)
end
tbody = html.create_element('tbody')
tbody.children = table.children
table.children = tbody
end
puts html.xpath('//table').to_s
__END__
<table border="0" cellspacing="5" cellpadding="5">
<tr><th>Header</th></tr>
<tbody>
<tr><td>Data</td></tr>
<tr><td>Data2</td></tr>
<tr><td>Data3</td></tr>
</tbody>
</table>
印刷品
<table border="0" cellspacing="5" cellpadding="5"><tbody>
<tr><th>Header</th></tr>
<tr><td>Data</td></tr>
<tr><td>Data2</td></tr>
<tr><td>Data3</td></tr>
</tbody></table>
这篇关于nokogiri:如何在表格标签之后立即插入 tbody 标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文