AlexQueue
AlexQueue

Reputation: 6551

Rails XML Feed: ID as node attribute

I set up a simple XML feed for a vendor we're using (who refuses to read JSON).

<recipes type="array">
  <recipe>
    <id type="integer">1</id>
    <name>
      Hamburgers
    </name>
    <producturl>
      http://test.com
    </producturl>
    ...
  </recipe>
  ...
<recipe>

However, the vendor requests that instead of having an id node, id is an attribute in the parent node. e.g.

<recipes type="array">
  <recipe id="1">
    <name>
      Hamburgers
    </name>
    <producturl>
      http://test.com
    </producturl>
    ...
  </recipe>
  ...
<recipe>

I'm building this with (basically)

xml_feed = []
recipes.each do |recipe|
  xml_feed <<{id: recipe.id, name: recipe.name, ...}
end
...
render xml: xml_feed.to_xml(root: 'recipes')

But I'm unsure of how to include the id (or any field) as an attribute in the parent node like that. I googled around and couldn't find anything, nor were the http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html docs very helpful

Thanks!

Upvotes: 0

Views: 167

Answers (2)

Kartzallis
Kartzallis

Reputation: 31

The suggestion to use Nokogiri is fine. Just the sintax should be a little bit different to achive what you have requested:

builder = Nokogiri::XML::Builder.new do |xml|
xml.root {
  xml.object('type' => 'Client') {
    xml.name 'John'
  }
}
end
puts builder.to_xml

<?xml version="1.0"?>
<root>
<object type="Client">
  <name>John</name>
</object>
</root>

Upvotes: 1

xlembouras
xlembouras

Reputation: 8295

I would suggest you use the nokogiri gem. It provides all you can possible need for handling XML.

builder = Nokogiri::XML::Builder.new do |xml|
xml.root {
  xml.objects {
    xml.object.classy.thing!
  }
}
end
puts builder.to_xml

<?xml version="1.0"?>
<root>
<objects>
  <object class="classy" id="thing"/>
</objects>
</root>

Upvotes: 1

Related Questions