浏览 2093 次
锁定老帖子 主题:ruby的rexml应用初步
该帖已经被评为新手帖
|
|
---|---|
作者 | 正文 |
发表时间:2008-10-04
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") 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间: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 |
|
返回顶楼 | |