Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to beautify xml code in rails application

Is there a simple way to print an unformated xml string to screen in a ruby on rails application? Something like a xml beautifier?

like image 671
Sebastian Müller Avatar asked Apr 11 '11 13:04

Sebastian Müller


1 Answers

Ruby core REXML::Document has pretty printing:

REXML::Document#write( output=$stdout, indent=-1, transitive=false, ie_hack=false )

indent: An integer. If -1, no indenting will be used; otherwise, the indentation will be twice this number of spaces, and children will be indented an additional amount. For a value of 3, every item will be indented 3 more levels, or 6 more spaces (2 * 3). Defaults to -1

An example:

require "rexml/document"

doc = REXML::Document.new "<a><b><c>TExt</c><d /></b><b><d/></b></a>"
out = ""
doc.write(out, 1)
puts out

Produces:

<a>
 <b>
  <c>
   TExt
  </c>
  <d/>
 </b>
 <b>
  <d/>
 </b>
</a>

EDIT: Rails has already REXML loaded, so you only have to produce new document and then write the pretty printed XML to some string which then can be embedded in a <pre> tag.

like image 181
Laas Avatar answered Sep 29 '22 21:09

Laas