Rails: rendering XML adds tag

前端 未结 2 764
有刺的猬
有刺的猬 2021-02-13 16:02

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

class MyController < ApplicationController
  # GET /example.xml
  de         


        
相关标签:
2条回答
  • 2021-02-13 16:27

    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 讨论(0)
  • 2021-02-13 16:28

    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>
    
    0 讨论(0)
提交回复
热议问题