Here's a much simpler version that creates a reliable hash that includes namespace information for both elements and attributes:
require 'nokogiri' class Nokogiri::XML::Node TYPENAMES = {1=>'element',2=>'attribute',3=>'text',4=>'cdata',8=>'comment'} def to_hash {kind:TYPENAMES[node_type],name:name}.tap do |h| h.merge! nshref:namespace.href, nsprefix:namespace.prefix if namespace h.merge! text:text h.merge! attr:attribute_nodes.map(&:to_hash) if element? h.merge! kids:children.map(&:to_hash) if element? end end end class Nokogiri::XML::Document def to_hash; root.to_hash; end end
In action:
xml = '<ra="b" xmlns:z="foo"><z:a>Hello <bz:m="n" x="y">World</b>!</z:a></r>' doc = Nokogiri::XML(xml) p doc.to_hash #=> { #=> :kind=>"element", #=> :name=>"r", #=> :text=>"Hello World!", #=> :attr=>[ #=> { #=> :kind=>"attribute", #=> :name=>"a", #=> :text=>"b" #=> } #=> ], #=> :kids=>[ #=> { #=> :kind=>"element", #=> :name=>"a", #=> :nshref=>"foo", #=> :nsprefix=>"z", #=> :text=>"Hello World!", #=> :attr=>[], #=> :kids=>[ #=> { #=> :kind=>"text", #=> :name=>"text", #=> :text=>"Hello " #=> }, #=> { #=> :kind=>"element", #=> :name=>"b", #=> :text=>"World", #=> :attr=>[ #=> { #=> :kind=>"attribute", #=> :name=>"m", #=> :nshref=>"foo", #=> :nsprefix=>"z", #=> :text=>"n" #=> }, #=> { #=> :kind=>"attribute", #=> :name=>"x", #=> :text=>"y" #=> } #=> ], #=> :kids=>[ #=> { #=> :kind=>"text", #=> :name=>"text", #=> :text=>"World" #=> } #=> ] #=> }, #=> { #=> :kind=>"text", #=> :name=>"text", #=> :text=>"!" #=> } #=> ] #=> } #=> ] #=> }
Phrogz Apr 13 2018-12-12T00: 00Z
source share