ruby的rexml应用初步

require "rexml/document"
include REXML    # so that we don’t have to prefix everything
# with REXML::...
$path = File.dirname(__FILE__)


class Readxml
 
  def initialize(file)
    @file = file
    @total = 0
    @doc  = Document.new File.new("#{$path}/../xmlfile/#{@file}")
  end
  def all()
    print @doc
  end
  def loadcolor()
    @doc.elements.each("guitars/make/model/color"){ |element| puts element.text }
  end
  def allprice()
    @doc.elements.each("guitars/make/model/price"){ |element| @total += element.text.to_i }
    puts "Total is $" + @total.to_s
  end
  def firstmodel(part,attribute = "")
    if part == "all"
      XPath.each( @doc, "//model/#{attribute}" ){ |element| puts element }
    else
      @model = XPath.first( @doc, "//model/#{attribute}" )
    end
   
    puts @model
  end

end
xmlf1=Readxml.new("guitars.xml")
xmlf1.load
xmlf1.loadcolor
xmlf1.allprice
xmlf1.firstmodel("all","attribute::year")




你可能感兴趣的:(xml,Ruby)