class Nokogiri::XML::Node

def to_hash

def to_hash
  { kind: TYPENAMES[node_type], name: name }.tap do |h|
    h[:text] = text&.strip
    a = attribute_nodes.map(&:to_hash)
    if element? && !a.empty?
      h[:attr] = a.inject({}) do |m, v|
        m[v[:name]] = v[:text]
        m
      end
    end
    c = children.map(&:to_hash)
    if element? && !(c&.size == 1 && c[0][:kind] == "text")
      h.merge! kids: c.delete_if { |n| n[:kind] == "text" && n[:text].empty? }
    end
  end
end