tags:

views:

150

answers:

2

I am going to be using Hpricot to process an XML file. I want to randomly display some quotes from the file, and then I want to keep track of how often each quote has been displayed. Is it possible for me to update a single item within the XML file using Hpricot (or is there some other solution that can do this for me?) or should I just rewrite the entire XML file each time an item is displayed?

+1  A: 

I used to work with nokogiri instead of hpricot (it is significantly faster).

I did something like this:

#!/usr/bin/env ruby
require 'rubygems'
require 'nokogiri'

FNAME = "/home/kirill/books.xml"

doc = Nokogiri::XML(open(FNAME))

doc.search('title').each {|node|
  node.content=node.content.reverse
}

File.new(FNAME,'w').write doc unless doc.validate

Do you have so large file this will be way to slow?

Or do you want something else I haven't understood?

kirushik
A: 

I see a couple of solutions:

  1. Parse the file once and store it in DB, and use additional attributes , viewed to keep a track.
  2. If DB is not available, parse it once and keep a Yaml. Easier to parse, read and write back. Will save you valuable execution time each time.

If you keep updating the file or synchronizing the file with a remote server, then storing the information in a DB is your best bet.

Swanand