开发者

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
e开发者_StackOverflow中文版nd

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>


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>


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!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜