Modifying an HTML / XML Document
Changing text contents
Assuming we have the following HTML document:
@doc = Nokogiri::HTML::DocumentFragment.parse <<-EOHTML
<body>
<h1>Three's Company</h1>
<div>A love triangle.</div>
</body>
EOHTML
Let’s change the header’s text contents:
h1 = @doc.at_css "h1"
h1.content = "Snap, Crackle and Pop"
@doc.to_html
# => "<body>
# <h1>Snap, Crackle and Pop</h1>
# <div>A love triangle.</div>
# </body>"
Pow!
Moving nodes
The simplest method of moving a node is assign its parent:
h1 = @doc.at_css "h1"
div = @doc.at_css "div"
h1.parent = div
@doc.to_html
# => "<body>
#
# <div>A love triangle.<h1>Three's Company</h1>
# </div>
# </body>"
But you could also arrange it next to other nodes:
div.add_next_sibling(h1)
@doc.to_html
# => "<body>
#
# <div>A love triangle.</div>
# <h1>Three's Company</h1>
# </body>"
Modifying Nodes and Attributes
h1.name = 'h2'
h1['class'] = 'show-title'
@doc.to_html
# => "<body>
# <h2 class=\"show-title\">Three's Company</h2>
# <div>A love triangle.</div>
# </body>"
Creating new nodes
h3 = Nokogiri::XML::Node.new "h3", @doc
h3.content = "1977 - 1984"
h1.add_next_sibling(h3)
@doc.to_html
# => "<body>
# <h1>Three's Company</h1>
# <h3>1977 - 1984</h3>
# <div>A love triangle.</div>
# </body>"
Wrapping a NodeSet
If you wanted to wrap new HTML around each node in a Nodeset, here’s an example of how to do it:
nodes = @doc.css "h1,div"
wrapper = nodes.wrap("<div class='container'></div>")
@doc.to_html
# =>
# ~> /home/miked/.gem/ruby/1.8/gems/nokogiri-1.4.2/lib/nokogiri/xml/node_set.rb:235:in `wrap': undefined method `parse' for nil:NilClass (NoMethodError)
# ~> from /home/miked/.gem/ruby/1.8/gems/nokogiri-1.4.2/lib/nokogiri/xml/node_set.rb:214:in `each'
# ~> from /home/miked/.gem/ruby/1.8/gems/nokogiri-1.4.2/lib/nokogiri/xml/node_set.rb:213:in `upto'
# ~> from /home/miked/.gem/ruby/1.8/gems/nokogiri-1.4.2/lib/nokogiri/xml/node_set.rb:213:in `each'
# ~> from /home/miked/.gem/ruby/1.8/gems/nokogiri-1.4.2/lib/nokogiri/xml/node_set.rb:234:in `wrap'
# ~> from -:6