From: Robert Klemme Date: 2005-06-24T17:55:38+09:00 Subject: Re: REXML Optimization Robert Klemme wrote: > Bucco wrote: >> So, I'm reading this document on XML and using XML as a database. Of >> course the author uses this cryptic perl script to parse the xml >> file: >> >> #!/usr/bin/perl >> use XML::LibXML; >> my $parser = new XML::LibXML; >> my $doc = $parser->parse_file( shift @ARGV ); >> my $balance = $doc->findvalue( '/checkbook/@balance-start' ); >> foreach my $record ( $doc->findnodes( '//debit' )) { >> $balance -= $record->findvalue( 'amount' ); >> } >> foreach my $record ( $doc->findnodes( '//deposit' )) { >> $balance += $record->findvalue( 'amount' ); >> } >> print "Current balance: $balance\n"; >> >> So, since I was trying to figure out how to use xml as a database and >> how to use REXML I gave the script a whack and tried to write a ruby >> script to do the same thing. Below is a sample of the xml file and >> the ruby script: >> >> >> >> expenses: january 2002 >> >> >> 31.19 >> 200213 >> Walking Store >> shoes >> >> >> >> 1549.58 >> 200217 >> Bob's Bolts >> >> >> >> >> #!/usr/bin/ruby -w >> require 'rexml/document' >> >> # Read in XML doc >> doc = REXML::Document.new(File.open('cb.xml')) >> # Future version need to have entry from command line >> >> # Find the balance and assign to float variabl 'balance' >> balance = doc.root.attributes['balanceStart'].to_f >> >> # Calculate debits and balance >> doc.elements.each("//debit/amount") {|o| balance -= o.text.to_f} >> # Calculate deposits and balance >> doc.elements.each("//deposit/amount") {|i| balance += i.text.to_f} >> >> #Display final balance: >> puts balance >> >> Of course I was able to complete the same task as teh perl script in >> ruby with less code. (Not to mention easier to read code) >> >> Just to help me complete the learning process, I wish to pose the >> question to the group: Is there a better way to do this, and is there >> more optimization I can do to my code? > > You could get rid of one traversal by iterating all "amounts" and do > the calculation based on the parent element's type. If you want to speed up things even more you can do stream processing with REXML's SAX like API: http://www.germane-software.com/software/rexml/docs/tutorial.html#id2248482 Kind regards robert