Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: rendering XML adds <hash> tag

I've got a Rails controller which is going to output a hash in XML format - for example:

class MyController < ApplicationController
  # GET /example.xml
  def index        
    @output = {"a" => "b"}

    respond_to do |format|
      format.xml  {render :xml => @output}
    end
  end
end

However, Rails adds a <hash> tag, which I don't want, i.e.:

<hash>
  <a>
    b
  </a>
</hash>

How can I just output this instead?

<a>
  b
</a>
like image 924
thomson_matt Avatar asked Jun 05 '11 08:06

thomson_matt


2 Answers

I think if you're converting an object to XML, you need a tag which wraps everything, but you can customise the tag name for the wrapper:

def index        
  @output = {"a" => "b"}

  respond_to do |format|
    format.xml  {render :xml => @output.to_xml(:root => 'output')}
  end
end

Which will result in:

<output>
  <a>
    b
  </a>
</output>
like image 133
theTRON Avatar answered Nov 01 '22 20:11

theTRON


I was having the same Issue;

This is my XML:

<?xml version="1.0" encoding="UTF-8"?>
<Contacts>
  <Contact type="array">
  </Contact>
</Contacts>

I was using this:

entries.to_xml

to convert hash data into XML, but this wraps entries' data into <hash></hash>

So I modified:

entries.to_xml(root: "Contacts")

but that still wrapped the converted XML in 'Contacts'. modifying my XML code to

<Contacts>
 <Contacts>
  <Contact type="array">
   <Contact>
    <Name></Name>
    <Email></Email>
    <Phone></Phone>
   </Contact>
  </Contact>
 </Contacts>
</Contacts>

So it adds an extra ROOT that I don't wan't there.

Now solution to this what worked for me is:

 entries["Contacts"].to_xml(root: "Contacts")

that avoids <hash></hash> or any additional root to be included. Cheers!!

like image 24
mayankcpdixit Avatar answered Nov 01 '22 18:11

mayankcpdixit