Ruby Pretty-Print XML

It’s fairly easy to do with some Rails libraries, although it’s different from the way that most people have suggested online due to Rails 3 changing the way that some things are laid out. If you want to use IRB or something else to pretty-print XML with Ruby, try the following:

require 'rubygems'
require 'ap'
include ActiveModel::Serializers::Xml

raw = File.read(filename)
parsed = Hash.from_xml(raw)
ap parsed

The ap is the awesome-print gem. It prints out the resultant structure in an easy-to-read format. I like the output of ap better than pp, and I like using RoR’s from_xml better than, say, REXML, Nokogiri, or XmlSimple. For the first two, you basically have to roll your own pretty-printer (from what I understand). XmlSimple works, but the output seems to be a bit funky (too many arrays for keys, etc.)

Check out my latest pretty-print script, which also does HTML and JSON real pretty-like: https://github.com/panozzaj/conf/blob/master/common/bin/pretty

Categories: development

« Ruby Shebang RVM No such file to load when running Ruby 1.9.2 on Ubuntu »

Comments