Never been to DZone Snippets before?

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 (See related posts)

From http://errtheblog.com/post/8
Simple XML is basically HTML with random tags, yeah? Parse it with Hpricot!

Your XML:
   1  
   2  <Export>
   3    <Product>
   4      <SKU>403276</SKU>
   5      <ItemName>Trivet</ItemName>
   6      <CollectionNo>0</CollectionNo>
   7      <Pages>0</Pages>
   8    </Product>
   9  </Export>


The code:
   1  
   2  require 'hpricot'
   3  FIELDS = %w[SKU ItemName CollectionNo Pages]
   4  
   5  doc = Hpricot.parse(File.read("my.xml"))
   6  (doc/:product).each do |xml_product|
   7    product = Product.new
   8    for field in FIELDS
   9      product[field] = (xml_product/field.intern).first.innerHTML
  10    end
  11    product.save
  12  end

You need to create an account or log in to post comments to this site.


Click here to browse all 5545 code snippets

Related Posts