--_dd5236a6-866b-4229-b324-0911de128a33_
Content-Type: text/plain; charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
I had not created a SAX listener before in Ruby. So, my solution reads theendor list in from XML. I noticed others were using this pastie thingy... I don't know what that is. Besides, pasties always seemed to be kind of pointless to me. They leave precious little to the imagination. So, belows the ruby file followed by the xml file:
---------------------------------------------------------------------------------
#!/usr/local/bin/ruby -w
require 'rexml/parsers/sax2parser'
require 'rexml/sax2listener'
class VendorListener
include REXML::SAX2Listener
def initialize(low, high)
begin
@low = Float(low)
rescue
@low = 0
end
begin
@high = Float(high)
rescue
#if someone can spend more than this then
#they can afford a better program
@high = 10**15
end
end
def start_element(uri, localname, tag_name, attrs)
if tag_name == 'Vendor'
@vendorName = attrs['name']
end
end
def end_element(uri, localname, tag_name)
if tag_name == 'Vendor'
if in_range?
puts @vendorName
end
elsif tag_name == 'LowPrice'
@lowPrice = Float(@data)
elsif tag_name == 'HighPrice'
@highPrice = Float(@data)
end
end
def characters(value)
@data = value
end
def in_range?
(@low >= @lowPrice and @low <= @highPrice) or
(@high >= @lowPrice and @high <= @highPrice) or
(@low < @lowPrice and @high > @highPrice)
end
end
puts "Enter a price range."
print "Enter low value: "
low = gets
print "Enter high value: "
high = gets
parser = REXML::Parsers::SAX2Parser.new(File.new('vendors.xml' ))
parser.listen(VendorListener.new(low, high))
parser.parse
puts "Program terminated."
---------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<Vendors>
<Vendor name="Company A">
<PriceRange>
<LowPrice>1000</LowPrice>
<HighPrice>3000</HighPrice>
</PriceRange>
</Vendor>
<Vendor name="Company B">
<PriceRange>
<LowPrice>6000</LowPrice>
<HighPrice>10000</HighPrice>
</PriceRange>
</Vendor>
<Vendor name="Company C">
<PriceRange>
<LowPrice>500</LowPrice>
<HighPrice>2500</HighPrice>
</PriceRange>
</Vendor>
</Vendors>
_________________________________________________________________
Make every e-mail and IM count. Join the iÃÎ Initiative from Microsoft.
http://im.live.com/Messenger/IM/Join/Default.aspx?source=EML_WL_ MakeCount-_dd5236a6-866b-4229-b324-0911de128a33_--