jruby で xhtml。 bodyタグ 内に 新たなタグを設ける

さて、またしても jrubyxhtml の続きです。
今度は、xhtml の bodyタグ 内に 新たなタグを設けてみます。


(そもそも私は、こんなことをやってて一体なにをしないのかな、とふと疑問に思ったりします。一般的な html エディタ よりもっと思い通りに html や xhtml を扱えないかなと思っているのは間違いありませんが、どうも自分自身で目指しているゴールがよく分からない…。まあ、とりあえず、気にしないことにしましょう)


とにかく、xhtml の bodyタグ 内に 新たなタグを設けます。
で、結果は下のサンプルの通り。


動作をテストした環境について。
jruby も nokogiri も日本語は utf-8 の使用が前提です)

jruby1.5.6
nokogiri1.4.4.2
ubuntu10.04 (文字環境は utf-8 がデフォルト)

では。この項、たぶんまだまだ続くと思います。


$KCODE = 'UTF8'

require 'rubygems'
require 'nokogiri'

@doc = Nokogiri::HTML(<<-EOHTML, nil, 'utf-8')
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>タイトル</title>
<style type="text/css">
</style>
</head>

<body>

</body>

</html>
EOHTML

puts "■ tag body 内に tag h1 を新たに設ける"
puts "■ 変更前の xhtml の内容"
puts @doc.to_xhtml(:encoding => 'UTF-8')

h1_obj = Nokogiri::XML::Node.new "h1", @doc
h1_obj.content = "見出し1"

body_obj = @doc.xpath("//body")[0]
body_obj.add_child(h1_obj)

puts "■ 変更後の xhtml の内容。tag h1 が増えている"
puts @doc.to_xhtml(:encoding => 'UTF-8')

=begin

実行結果
■ tag body 内に tag h1 を新たに設ける
■ 変更前の xhtml の内容
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>タイトル</title>
<style type="text/css">
<![CDATA[
]]>
</style>
</head>
<body>

</body>
</html>
■ 変更後の xhtml の内容。tag h1 が増えている
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>タイトル</title>
<style type="text/css">
<![CDATA[
]]>
</style>
</head>
<body>

<h1>見出し1</h1></body>
</html>

=end