nokogiri:如何在表标签后立即插入tbody标签?

时间:2010-04-21 05:14:20

标签: nokogiri

我想确保所有桌子的直接孩子都是t .. ....

我怎么能用xpath或nokogiri写这个?

 doc.search("//table/").each do |j|
  new_parent = Nokogiri::XML::Node.new('tbody',doc)
  j.replace  new_parent
  new_parent << j
 end

1 个答案:

答案 0 :(得分:2)

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>
相关问题