The code could look much better and needs some checks, it could be much more efficient and elegant as well.
It's doing the job, so I'm guessing that should count for something.
The assumption is that the tags will self-close when they don't have children.
Ruby
class Node
attr_accessor :tag, :attr, :children
def initialize( tag, attr )
@tag = tag
@attr = attr
self.children = []
end
def add_children( children )
# add check to make sure they are nodes
children.each do |c|
self.children << c
end
end
def has_children?
self.children != [] ? true : false
end
def print_all
if self.has_children? == true
self.print_open( true )
self.children.each do |c|
c.print_all
end
self.print_close
else
self.print_open( false )
end
end
def print_open( children_flag )
if self.attr != {}
print "<#{tag} "
self.attr.each{ |k,v| print "#{k}=\"#{v}\" " }
print children_flag ? ">\n" : "/>\n"
else
puts children_flag ? "<#{tag}>" : "<#{tag} />"
end
end
def print_close
puts "</#{tag}>"
end
end
auditorium = Node.new( "Auditorium", {} )
roula = Node.new( "Person", { :name => "roula", :sex => "female" } )
omar = Node.new( "Person", { :name => "omar", :sex => "male" } )
raul = Node.new( "Baby", { :name => "raul", :sex => "male" })
auditorium.add_children( [roula, omar] )
omar.add_children( [raul] )
auditorium.print_all
<Auditorium>
<Person name="roula" sex="female" />
<Person name="omar" sex="male" >
<Baby name="raul" sex="male" />
</Person>
</Auditorium>