views:

1812

answers:

3

I have the following HTML:

<html>
<body>
<h1>Foo</h1>
<p>The quick brown fox.</p>
<h1>Bar</h1>
<p>Jumps over the lazy dog.</p>
</body>
</html>

...and by using the RubyGem Nokogiri (a hpricot replacement), I'd like to change it into the following HTML:

<html>
<body>
<p class="title">Foo</p>
<p>The quick brown fox.</p>
<p class="title">Bar</p>
<p>Jumps over the lazy dog.</p>
</body>
</html>

In other words: How can I find and replace certain HTML tags by using Nokogiri? I know how to find them (using css keywords), but I don't know how to replace them while parsing the document.

Thanks for your help!

+8  A: 

Try this:

require 'nokogiri'

html_text = "<html><body><h1>Foo</h1><p>The quick brown fox.</p><h1>Bar</h1><p>Jumps over the lazy dog.</p></body></html>"

frag = Nokogiri::HTML(html_text)
frag.xpath("//h1").each { |div|  div.name= "p"; div.set_attribute("class" , "title") }
SimonV
This solution is really elegant! Thanks a lot!
Javier
Do you know how to make a css-search to find a div with an id and a class? Example: <div id='foo' class='bar'>XXX</div>?
Javier
frag.xpath("//div[@id='foo' and @class='bar']")
SimonV
+4  A: 

Seems like this works right:

require 'rubygems'
require 'nokogiri'

markup = Nokogiri::HTML.parse(<<-somehtml)
<html>
<body>
<h1>Foo</h1>
<p>The quick brown fox.</p>
<h1>Bar</h1>
<p>Jumps over the lazy dog.</p>
</body>
</html>
somehtml

markup.css('h1').each do |el|
  el.name = 'p'
  el.set_attribute('class','title')
end

puts markup.to_html
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"&gt;
# >> <html><body>
# >> <p class="title">Foo</p>
# >> <p>The quick brown fox.</p>
# >> <p class="title">Bar</p>
# >> <p>Jumps over the lazy dog.</p>
# >> </body></html>
dylanfm
This solution works too.
Javier
+2  A: 
#!/usr/bin/env ruby
require 'rubygems'
gem 'nokogiri', '~> 1.2.1'
require 'nokogiri'

doc = Nokogiri::HTML.parse <<-HERE
  <html>
    <body>
      <h1>Foo</h1>
      <p>The quick brown fox.</p>
      <h1>Bar</h1>
      <p>Jumps over the lazy dog.</p>
    </body>
  </html>
HERE

doc.search('h1').each do |heading|
  heading.name = 'p'
  heading['class'] = 'title'
end

puts doc.to_html
Jörg W Mittag
This solution works.
Javier