Nokogiri: how to insert a tag tag right after the table tag?

I want to make sure all child tables of the table are dark ....

how can i write this using 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

      

+2


a source to share


1 answer


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>

      

prints



<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>

      

+2


a source







All Articles