views:

436

answers:

2

Hello

I am trying to send send an xml Doc from an action

The XML is created by the following method

def media_xml 
 x = Builder::XmlMarkup.new
 x.instruct!
 x.declare! :DOCTYPE, :html, :PUBLIC, "-//W3C//DTD XHTML 1.0 Strict//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
 x.options{
  x.videos{
   for m in self.media
    x.imageName("static-video-image.png", "target"=>"_self", "html"=>"", "flv"=> m.filename+".flv", "autoStart"=>"false")
   end
  }
 }
 x
end

In the controller I use the following

def media
 @inspection = @tag.inspections.find params[:id]
 respond_to do |format|
     format.html { render :nothing => true }
     format.xml { render :xml => @inspection.media_xml }
 end
end

And the following XML is the result

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<options>
  <videos>
    <imageName html="" flv="3504_1245270846028.flv" autoStart="false" target="_self">static-video-image.png</imageName>
  </videos>
</options>

<respond_to?:to_xml/><to_xml/>

Because of the "<respond_to?:to_xml/><to_xml/>" the parser on the other end gives the following error

XML Parsing Error: junk after document element

Why does rails put this in the document and how do i get rid of it?

Thank you!

+1  A: 

Turns out that what was happening is the Builder::XmlMarkup.new was being returned from the media_xml method

This caused any subsiquent calls on that object to add more tags instead of calling the function.

def media_xml 
    x = Builder::XmlMarkup.new
    x.instruct!
    x.declare! :DOCTYPE, :html, :PUBLIC, "-//W3C//DTD XHTML 1.0 Strict//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
    x.options{
            x.videos{
                    for m in self.media
                            x.imageName("static-video-image.png", "target"=>"_self", "html"=>"", "flv"=> m.filename+".flv", "autoStart"=>"false")
                    end
            }
    }
    #x <= removing this fixed the problem
end
rube_noob
A: 

Hey, Thank you so much! Was having the same problem and was scratching my head trying to figure out what on earth is happening.

I had a simple function like this

def media_xml
  request =  Builder::XmlMarkup.new

  request.instruct! :xml, :version => "1.0", :encoding=>"UTF-8"

  request.favourites{
    request.food("banana") 
  }

  render :xml => media_xml
end

.. and it was giving that same stupid error. So after reading your post, i separated the xml builder to another function

def build_xml
  request =  Builder::XmlMarkup.new

  request.instruct! :xml, :version => "1.0", :encoding=>"UTF-8"

  request.favourites{
    request.food("banana") 
  }
end

As it turns out even if I put a single line at the end of the 'build_xml()' function like "return request", it will create an error because it tries to add that to the XML object.

Vicer