DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Parse XML With Hpricot
From <a href="http://errtheblog.com/post/8">http://errtheblog.com/post/8</a>
Simple XML is basically HTML with random tags, yeah? Parse it with <a href="http://redhanded.hobix.com/inspect/hpricot01.html">Hpricot</a>!
Your XML:
<Export>
<Product>
<SKU>403276</SKU>
<ItemName>Trivet</ItemName>
<CollectionNo>0</CollectionNo>
<Pages>0</Pages>
</Product>
</Export>
The code:
require 'hpricot'
FIELDS = %w[SKU ItemName CollectionNo Pages]
doc = Hpricot.parse(File.read("my.xml"))
(doc/:product).each do |xml_product|
product = Product.new
for field in FIELDS
product[field] = (xml_product/field.intern).first.innerHTML
end
product.save
end





