Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Convert XML to Haml (See related posts)

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



You need to create an account or log in to post comments to this site.


Click here to browse all 5137 code snippets

Related Posts