Skip to content

Instantly share code, notes, and snippets.

@ezkl
Created August 1, 2011 21:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ezkl/f357da62d5fde62fdd7d to your computer and use it in GitHub Desktop.
Save ezkl/f357da62d5fde62fdd7d to your computer and use it in GitHub Desktop.
Nokogiri Test
require 'nokogiri'
html = <<HTML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Foo</title>
</head>
<body>
<p>Lorem ipsum</p>
</body>
</html>
HTML
puts "Original"
puts "======================"
puts html
puts "======================"
doc = Nokogiri::HTML(html)
puts "Original After Parsing"
puts "======================"
puts doc.to_s
puts "======================"
doc.css("body").first.inner_html = "<h1>Lorem ipsum</h1>"
puts "After <body> change"
puts "======================"
puts doc.to_s
puts "======================"
File.open("path/to/test.html", "w") { |f| f.write doc }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<?xml version="1.0" encoding="UTF-8"?><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Foo</title>
</head>
<body><h1>Lorem ipsum</h1></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment