论坛首页 入门技术论坛

ruby的rexml应用初步

浏览 2093 次
该帖已经被评为新手帖
作者 正文
   发表时间:2008-10-04  
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")




   发表时间:2008-10-04  
require "rexml/document"
include REXML    # so that we don’t have to prefix everything with
                 # REXML::...

doc = Document.new File.new("guitars.xml")

root = doc.root

make = Element.new "make"
make.attributes["name"] = "Gibson"

model = Element.new "model"
model.attributes["sn"]      = "99999999"
model.attributes["year"]    = "2007"
model.attributes["country"] = "USA"

model.add_element "name"
model.elements["name"].text  = "SG"
model.add_element "price"
model.elements["price"].text = "1250.00"
model.add_element "color"
model.elements["color"].text = "Red"

make.add_element model

root.add_element make

print doc
0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics