1

I have an array of user objects which I want to return as xml. How can I use to_xml to include attributes on the root element? For example

    <users total="10">
      <user>
      ..
      </user>
    </users>

I know you can add custom elements and attributes to the xml using a block with the to_xml method, but I'm not sure how to add to the root element. Maybe there's another way other than using to_xml

1 Answer 1

1

I have used xml builder. Following code snippet covers some tricky xml building.

In you controller,

require 'builder'

def show_xml
  @xml = get_xml_data
  respond_to do |format|
    format.html # show.html.erb
    format.xml { render :xml => @xml }
  end
end

def get_xml_data
  xml = Builder::XmlMarkup.new#(:target=>$stdout, :indent=>2)
  xml.instruct! :xml, :version => "1.0", :encoding => "US-ASCII"
  xml.declare! :DOCTYPE, :html, :PUBLIC, "-//W3C//DTD XHTML 1.0 Strict//EN",  
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
  favorites = {
    'candy' => 'Neccos', 'novel' => 'Empire of the Sun', 'holiday' => 'Easter'
  }

  xml.favorites do
    favorites.each do | name, choice |
     xml.favorite( choice, :item => name )
    end
  end
end
Sign up to request clarification or add additional context in comments.

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.