1

I need to create an XML file output like:

<data>
    <hour>0</hour>
    <count>8</count>
</data>
.
.
<data>
    <hour>23</hour>
    <count>1</count>
</data>

I wrote the following code in my controller:

for @k in (0..23)
  @data.push(Datum.new(@k,@freq[@k]));
end

class Datum  
  def initialize(hour, count)  
    @hour = hour  
    @count = count  
  end  
end

render xml:@data

But the output comes out like:

    tweet-densities-controller-data type="array">
    <tweet-densities-controller-datum type="TweetDensitiesController::Datum">#
    TweetDensitiesController::Datum:0xacbddc4></tweet-densities-controller-datum>

2 Answers 2

2

You may want to take a look at builder: Generating custom XML for your rails app

Sign up to request clarification or add additional context in comments.

Comments

0

What is happening here is that when you do render :xml => @data Rails is trying to convert @data (which is an Array) to its XML representation. This is not what you want in this case.

Define a #to_xml method on your Datum class and then you can do something like:

@data.map(&:to_xml).join("\n")

Which will call the #to_xml method for every object and then you'll concatenate them, separating each entry by a newline.

If you want well-structured XML data (doesn't seem like it from your example) then you should use something like Builder as suggested by jessecurry.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.