Extra <to_s/> when using builder to generate XML Extra <to_s/> when using builder to generate XML xml xml

Extra <to_s/> when using builder to generate XML


My short original answer

To get the actual string contents of the Builder you need to call the method target!

xml = Builder.new# do your stuff...xml.target! #returns the string#where as calling most other methods (like to_s) to the builder object will just#generate an element tag by that method name.


And then a bit more verbose explanation of what and why is going on in the OPs case

When you pass the xml builder object to the render method Rails will automatically call the to_s method for it. Usually this means that you do not need to worry about the type of data that you pass for the renderer, since it will be converted to a String anyway. Very convenient! However, with the Builder object you need to do the conversion your self since the builder assumes that any message sent to it is a request to add a new element by the name. So calling xml.to_s behaves just the same as calling xml.kml, adds a new element. In this case your not calling to_s your self so it is not so apparent and is easy to miss. The simple fix to this is to call render like this:

render :text => xml.target!, :type=>"text/kml"


You don't need to initialize an XML builder object. Just use the integrated builder template handler.

  1. Call the template kml2dot2.xml.builder
  2. Write the code directly in the view

Example

def kml2dot2  @site = Site.find(params[:id])end# kml2dot2.xml.builderxml.kml("xmlns" => "http:// www.opengis.net/kml/2.2") do  xml.Placemark do    xml.name @site.mapNameFull    xml.Point do       xml.coordinates "#{@site.lat},#{@site.lng},0"    end  endend