> Would probably be pretty easy to see how Rails does it, and then just
> modify it as needed to use libxml.  Patches always welcome :)
>
> Charlie
>

Hey Charlie.

Here is what I came up with. It mimics the rails method in that it
does not deal with attributes. It also doesn't do anything with
namespaces either. Frankly I don't quite know how I would deal those
issues anyway.

I am a fairly new rubyist so this code may not be up to your
standards, feel free to do with it what you will.

class LibXML::XML::Node
  def has_duplicate_elements?
    a=[]
    self.each_element do |c|
      return true if a.include? c.name
      a << c.name
    end
    return false
  end

  def node_to_hash (node)
    if not node.children?
      nil
    elsif (node.children.count == 1 && node.first.text?) ||
node.empty?
      node.content
    elsif node.has_duplicate_elements?
      a =[]
      node.each_element do |e|
        a << {e.name => node_to_hash(e)}
      end
      a
    else
      h = {}
      node.each_element { |e|
        h[e.name] = node_to_hash(e)
      }
      h
    end
  end
  def to_hash
    h={}
    h[self.name] = node_to_hash(self)
    h
  end
end
_______________________________________________
libxml-devel mailing list
libxml-devel@rubyforge.org
http://rubyforge.org/mailman/listinfo/libxml-devel

Reply via email to