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

About this user

James Robertson http://www.r0bertson.co.uk

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Convert XML to Haml

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


Running Haml stand-alone

This Ruby code converts HAML to XHTML. code based on the example given at 'A HAML Server for Web Designers' http://urltea.com/23j8 [wiseheartdesign.com].

require 'rubygems'
require 'haml'

def parse_haml(string)
  engine = Haml::Engine.new(string)
  engine.render
end

parse_haml("#hello")


Note: The above code worked on Ubuntu 7.10, and on Gentoo I declared require 'haml/engine' as an alternative to requiring 'rubygems' and 'haml'.
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS