From: Tobias Reif Date: 2002-03-18T01:43:20+09:00 Subject: Re: XPath Michael Schuerig catalogs books, and asked for help: ----------8<---------- $:.unshift 'rexml/1.2.6/' require 'rexml/document' include REXML OLD = < Thomas, David; Hunt, Andrew english Addison-Wesley Programming Ruby. The Pragmatic Programmer's Guide 2000 Blammo, Blah english Hubbabubba Foozboozer's Life Book 2002 DELIMITER CURRENT = < english Addison-Wesley Programming Ruby. The Pragmatic Programmer's Guide Book 2000 Blammo, Blah english Hubbabubba Foozboozer's Life Book 2002 DELIMITER #MS = you, Mr. schuerig@acm.org #MS: Read in both versions of the file OLD_TREE = Document.new OLD goal_tree = Document.new CURRENT.dup #puts OLD_TREE,goal_tree XPath.each goal_tree, '/biblio/entry' do |entry| #MS: For each "dubious" entry in the current file unless XPath.first(entry, '//author') title = XPath.first(entry, '//title').text year = XPath.first(entry, '//year').text #MS: Find a corresponding (based on title and year) entry #MS: in the original file XPath.each(OLD_TREE,"//entry") do |e| title_test = XPath.first(e, '//title').text == title year_test = XPath.first(e, '//year').text == year if title_test and year_test @author = XPath.first(e, '//author') end end #/author .text #XPath.first(needed_entry author #puts needed_entry #MS: Fix the current entry entry.insert_before XPath.first(entry, '//language'), @author #puts title end end print goal_tree.to_s.gsub(/>\s*\n<") #MS: Dump a fixed file =begin Thomas, David; Hunt, Andrew english Addison-Wesley Programming Ruby. The Pragmatic Programmer's Guide Book 2000 Blammo, Blah english Hubbabubba Foozboozer's Life Book 2002 =end # This is a pretty quirky way to do it. # Part of the problem is my limited time, # part of it is that REXML's current XPath support is limited. # 1. You and/or others can optimize the above, and make it more elegant. # 2. If memory becomes a problem think about streaming APIs. # 3. You might want to think about ISBNs. # 4. You might want to wait for REXML 2.0 # 5. The thing should @ least give you a start ;) ----------8<---------- Tobi -- * peace&love. * http://www.pinkjuice.com/