nokogiri: how to insert tbody tag immediately afte

2019-05-22 16:44发布

i want to make sure all table's immediate child is tbody....

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

标签: nokogiri
1条回答
Luminary・发光体
2楼-- · 2019-05-22 17:01
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>
查看更多
登录 后发表回答