How to beautify xml code in rails application

匿名 (未验证) 提交于 2019-12-03 02:48:02

问题:

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

回答1:

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.



回答2:

What about the Nokogiri gem? Here is an example use.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!