[libxml-devel] doc.to_hash, node.to_hash, xpath.to_hash
Charlie Savage
cfis at savagexi.com
Tue Jan 20 05:00:45 EST 2009
Hey Tim,
> 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.
Cool. So I assume you want this to be a drop in replacement for
whatever Rails is using now (REXML I assume?). Does Rails have a test
suite for outputting xml that you can test against?
If we can prove this actually works, then maybe we wrap it up as an
optional module included in libxml that you could require in code?
> 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
At a quick glance it seems ok....
Charlie
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3237 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://rubyforge.org/pipermail/libxml-devel/attachments/20090120/a07c022b/attachment.bin>
More information about the libxml-devel
mailing list