Rails 3: Parsing XML

Posted by gjb on Stack Overflow See other posts from Stack Overflow or by gjb
Published on 2010-11-03T17:50:41Z Indexed on 2011/01/05 6:53 UTC
Read the original article Hit count: 418

I have a simple XML document in the following format:

<?xml version="1.0" encoding="utf-8"?>
<object>
  <strField>Foo</strField>
  <intField>1</intField>
  <dateField>2010-11-03</dateField>
  <boolField>true</boolField>
  <nilField></nilField>
</object>

I would like to parse this into a Hash to be passed to Model.create:

{:object => {
  :strField  => 'Foo',
  :intField  => 1,
  :dateField => Date.today,
  :boolField => true,
  :nilField  => nil }}

Sadly there are no "type" attributes in the XML, so using Hash.from_xml just parses each field as a string. What I am looking for is some sort of field type auto detection. I have also looked at Nokogiri, but that can't output as a Hash.

What is the simplest and most efficient way to achieve this?

Many thanks.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby