Search code examples
ruby-on-railsxmlrespond-to

XML Parsing Error: junk after document element. Rails builder


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


Solution

  • 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