require 'rexml/document' include REXML def compact(node,indent) if(node.class==Element) print node.name+"[" indent += ' '*(node.name.length+1); first=true; node.attributes.each do |key,value| print "\n#{indent}" unless first print "@#{key}[#{value}]" first=false; end node.children.each do |child| # deal only with element nodes or non-"empty" text nodes if child.class==Element || child.value.strip.length>0 print "\n#{indent}" unless first compact(child,indent) first=false; end end print "]" elsif node.class==Text print node.value.strip.gsub(/ *\n */," ") # normalize new lines end end doc = Document.new(STDIN) compact(doc.root,"")