This Ruby code converts a simple XML document into HAML.
require 'rexml/document'
include REXML
fruit = "<fruit><apple country='france' month='august'>tasty<gdelicious/></apple><pear></pear></fruit>"
doc_fruit = Document.new(fruit)
def xml2haml(nodex, indent ='')
nodex.elements.each do |node|
attributex = ' '
buffer = indent + '%' + node.name
if node.attributes.size > 0 then
alist = Array.new(node.attributes.size)
i = 0
node.attributes.each { |x, y|
alist[i] = " :#{x} => '#{y}'"
i += 1
}
attributex = '{' + alist.join(",") + '} '
end
buffer += attributex + node.text if not node.text.nil?
puts buffer
xml2haml(node, indent + ' ')
end
end
xml2haml(doc_fruit)
output:
%fruit
%apple{ :month => 'august', :country => 'france'} tasty
%gdelicious
%pear