HowTo: Parse XML using Hpricot
October 10, 2008 1 Comment
This requires the hpricot plugin.
This is the xml file to be parsed.
<holiday>
<date>
<year>2008</year>
<month>09</month>
<day>23</day>
<type>private</type>
<description>test</description>
</date>
<date>
<year>2008</year>
<month>09</month>
<day>24</day>
<type>company</type>
<description>test2</description>
</date>
<date>
<year>2008</year>
<month>09</month>
<day>25</day>
<type>national</type>
<description>test3</description>
</date>
</holiday>
I put the method in a helper class.
def is_holiday(the_date)
type = “none”
xml_file = File.read(“#{RAILS_ROOT}/public/holiday.xml”)
doc = Hpricot::XML(xml_file)
(doc/:date).each do |xml_date|
if the_date.strftime(“%Y”) == xml_date.at(“year”).innerHTML &&
the_date.strftime(“%m”) == xml_date.at(“month”).innerHTML &&
the_date.strftime(“%e”) == xml_date.at(“day”).innerHTML
then
return type = xml_date.at(“type”).innerHTML
end
end
return type #none
end
Using the helper method, you can check if a date is a holiday either in your controller or view.
Alternatives:
REXML or libxml (I haven’t tried these yet, as hpricot was said to be faster)
References:
Parsing XML with Ruby
Parsing XML quickly
Parse XML with Hpricot
Enjoy
Update:
for xml like this: <date year=”2008″ month=”01″ day=”01″ type=”pulic”>test holiday</date>
you can access it using xml_date.attributes["month"]