hpricot:An Hpricot Showcase:Hpricot Altering:Altering Elements

まんま

>> require "hpricot"
=> true
>> doc = Hpricot("That's my <b>spoon</b>, Tyler.")
=> #<Hpricot::Doc "That's my " {elem <b> "spoon" </b>} ", Tyler.">
>> doc.at("b").swap("<i>fork</i>")
=> [{elem <i> "fork" </i>}]
>> doc.to_html
=> "That's my <i>fork</i>, Tyler."
>> doc.at("i").swap { em "grapefruit spoon" }
TypeError: can't convert Hpricot::ETag into String
   ...
>> doc.to_html
=> "That's my <em>grapefruit spoon</em>, Tyler."


まんま

>> require "hpricot"
=> true
>> doc = Hpricot("<html>Remove this: <b>here</b></html>")
=> #<Hpricot::Doc {elem <html> "Remove this: " {elem <b> "here" </b>} </html>}>
>> doc.search("b").remove
=> #<Hpricot::Elements[{elem <b> "here" </b>}]>
>> doc.to_html
=> "<html>Remove this: </html>"


まんま

>> require "hpricot"
=> true
>> doc = Hpricot('<html><a href="http://www.foo.org/">foo</a><a href="http://www.bar.org/">bar</a></html>')
=> #<Hpricot::Doc {elem <html> {elem <a href="http://www.foo.org/"> "foo" </a>} {elem <a href="http://www.bar.org/"> "bar" </a>} </html>}>
>> doc.search('//a[@href]') do |link|
?>   href = URI(link.attributes['href']) rescue nil
>>   next unless href && href.host
>>   link.after '<span style="font-size:8px">[' + href.host + ']</span>'
>> end
=> #<Hpricot::Doc {elem <html> {elem <a href="http://www.foo.org/"> "foo" </a>} {elem <span style="font-size:8px"> "[www.foo.org]" </span>} {elem <a href="http://www.bar.org/"> "bar" </a>} {elem <span style="font-size:8px"> "[www.bar.org]" </span>} </html>}>


まんま

require "hpricot"

doc = Hpricot('<html><p>foo</p><p>bar</p></html>')
doc.at('p').before do
  pre Hpricot::Tag::CData.new <<-'CDATA'
        <some>
            <example>
                <xml/>
            </example>
        </some>
  CDATA
end
puts doc.to_html

で、

<html><pre><![CDATA[        <some>
            <example>
                <xml/>
            </example>
        </some>
]]></pre><p>foo</p><p>bar</p></html>

例では、「end」多くない?