forked from hpricot/hpricot
-
Notifications
You must be signed in to change notification settings - Fork 15
Hpricot Altering
i5m edited this page Sep 13, 2010
·
1 revision
(Part of An Hpricot Showcase.)
When you alter Hpricot elements in a list, your changes will be reflected in
the document you started searching from.
doc = Hpricot("That's my <b>spoon</b>, Tyler.")
doc.at("b").swap("<i>fork</i>")
doc.to_html
# => "That's my <i>fork</i>, Tyler."
Using Builder-style methods (Hpricot 0.6 and up):
#!ruby
doc.at("i").swap { em "grapefruit spoon" }
doc.to_html
# => "That's my <em>grapefruit spoon</em>, Tyler."
Want to remove something?
# Remove all elements in this list from the document which contains them.
doc = Hpricot("<html>Remove this: <b>here</b></html>")
doc.search("b").remove
doc.to_html
# => "<html>Remove this: </html>"
Adding HTML after an element:
document.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
Adding CDATA:
document.at('p').before do
pre Hpricot::Tag::CData.new <<-'CDATA'
<some>
<example>
<xml/>
</example>
</some>
CDATA
end
end
Return to An Hpricot Showcase.