nokogiri: how to insert tbody tag immediately after table tag?

自古美人都是妖i 提交于 2019-12-08 00:08:18

问题


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

回答1:


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>


来源:https://stackoverflow.com/questions/2680479/nokogiri-how-to-insert-tbody-tag-immediately-after-table-tag

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!