views:

36

answers:

2

I created a controller having an action:

def gen_books_xml
  @books = Book.find(:all, :conditions => {:owner_id => 1})
  respond_to do |format|
    format.xml { render :xml => @books.to_xml(:root => "Books", :skip_types=>true) }
  end
end

How could I implement the to_xml method in the Book model sa that it can generate the following format?

<?xml version="1.0" encoding="UTF-8"?>
<Books>
  <Owner>1</Owner>
  <Book><title>some title</title></Book>
  <Book><title>some title</title></Book>
  <Book><title>some title</title></Book>
  ...
</Books>

where there is only 1 Owner element and many Book elements

I can only output the Book elements but cannot output the one Owner in the same level of Books. Please HELP!!!

A: 

not solution, but hack

@books.to_xml(...).sub("<Books>","<Books><Owner>1</Owner>")
zed_0xff
Thank you for responding so fast! It seemed that it produced the correct document, but also the following error message: This page contains the following error message: error on line 3 at column 1: Extra content at the end of the document Below is a rendering of the page up to the first error.
PeterWong
Oh sorry! I've got the problem. I used <Owner>1</Owner> instead of <Books><Owner>1</Owner>. The problem have been solved, although it is a hack, thank you!
PeterWong
can you post an entire XML document that was generated?
zed_0xff
then please put the green checkmark under my answer :)
zed_0xff
new to stackoverflow and didn't know the checkmark^^|| checked now, thx
PeterWong
A: 

You should build it with Rails XML Builder, but be careful with the naming convention. PS, the examples are not tested, there might be some errors, use at your own judgement. Change your controller like so:

def gen_books_xml
  @owner_id = 1
  @books = Book.find(:all, :conditions => {:owner_id => @owner_id})
  respond_to do |format|
    format.xml
  end
end

Now, you have @owner_id and @books accessible from your views. Then create the builder file in views/controller_name/gen_books_xml.xml.builder:

xml.instruct!              # for the <?xml version="1.0" encoding="UTF-8"?> line
xml.books do               # xml.foo creates foo element
  xml.owner @owner_id      # you're inside a block so xml.bar will create <foo><bar/></foo> elements
  @books.each do |book|
    xml.book do
      xml.title book.title
    end
  end
end

You can modify this builder to make the XML look however you like.

Cem Catikkas