XML要素をツリー解析し、その要素にアクセスする
次は、XML文書を解析し、REXMLでXML文書内の要素にアクセスする方法を見てみます。まず、次のようなXML文書「guitars.xml」を作成します。
<guitars title="My Guitars"> <make name="Fender"> <model sn="123456789" year="2006" country="japan"> <name>62 Reissue Stratocaster</name> <price>750.00</price> <color>Fiesta Red</color> </model> <model sn="112233445" year="2006" country="mexico"> <name>60s Reverse Headstock Stratocaster</name> <price>699.00</price> <color>Olympic White</color> </model> </make> <make name="Squier"> <model sn="445322344" year="2003" country="China"> <name>Standard Stratocaster</name> <price>179.99</price> <color>Cherry Sunburst</color> </model> </make> </guitars>
この「guitars.xml」を、REXMLを使用して読み込み、プリントします。そのためには、次のような内容のRubyファイル「REXMLFileTest.rb」を作成します。
require "rexml/document" include REXML # so that we don't have to prefix everything # with REXML::... doc = Document.new File.new("guitars.xml") print doc
「REXMLFileTest.rb」を実行すると、次のようなプリント結果が表示されます。
今度は、文書内の一部の情報をプリントしてみましょう。まず、この文書に記載されているギターの色をすべてプリントします。それには、文書中の個々のguitars/make/model/color要素にアクセスし、要素内のテキストをプリントします。
include REXML # so that we don't have to prefix everything # with REXML::... doc = Document.new File.new("guitars.xml") doc.elements.each("guitars/make/model/color") { |element| puts element.text }
Rubyスクリプトを再度実行すると、ギターの色がプリントされます。
次に、これらのギターの値段を合計します。各price要素をtotalに加算し、そのtotalをプリントします。
require "rexml/document" include REXML # so that we don't have to prefix everything with # REXML::... doc = Document.new File.new("guitars.xml") # print doc # doc.elements.each("guitars/make/model/color") # { |element| puts element.text } total = 0 doc.elements.each("guitars/make/model/price") { |element| total += element.text.to_i } puts "Total is $" + total.to_s
このスクリプトを実行すると、次のように出力されます。



