有没有一种简单的方法可以将Nokogiri XML文档转换为哈希?

比如Rails'Hash.from_xml.

推荐答案

我在libxml ruby(1.1.3)中使用了这段代码.我自己没有使用过nokogiri,但我知道它使用的是libxml ruby.我还鼓励您看看ROXML(http://github.com/Empact/roxml/tree),它将xml元素映射到ruby对象;它构建在libxml之上.

# USAGE: Hash.from_libxml(YOUR_XML_STRING)
require 'xml/libxml'
# adapted from 
# http://movesonrails.com/articles/2008/02/25/libxml-for-active-resource-2-0

class Hash 
  class << self
        def from_libxml(xml, strict=true) 
          begin
            XML.default_load_external_dtd = false
            XML.default_pedantic_parser = strict
            result = XML::Parser.string(xml).parse 
            return { result.root.name.to_s => xml_node_to_hash(result.root)} 
          rescue Exception => e
            # raise your custom exception here
          end
        end 

        def xml_node_to_hash(node) 
          # If we are at the root of the document, start the hash 
          if node.element? 
           if node.children? 
              result_hash = {} 

              node.each_child do |child| 
                result = xml_node_to_hash(child) 

                if child.name == "text"
                  if !child.next? and !child.prev?
                    return result
                  end
                elsif result_hash[child.name.to_sym]
                    if result_hash[child.name.to_sym].is_a?(Object::Array)
                      result_hash[child.name.to_sym] << result
                    else
                      result_hash[child.name.to_sym] = [result_hash[child.name.to_sym]] << result
                    end
                  else 
                    result_hash[child.name.to_sym] = result
                  end
                end

              return result_hash 
            else 
              return nil 
           end 
           else 
            return node.content.to_s 
          end 
        end          
    end
end

Ruby相关问答推荐

Ruby 中使用的-S标志是什么?

ASDF 上缺少 Ruby 版本

在 Ruby 中使用委托维护相同的类

Ruby 是否提供了一种使用指定编码执行 File.read() 的方法?

如何增加 ruby​​ 应用程序的堆栈大小.递归应用程序获取:堆栈级别太深(SystemStackError)

如何在 Sinatra 中解析 JSON 请求正文一次并将其公开给所有路由?

Ruby检测方法

在 Ruby 中创建数字、字符串、数组或哈希的 md5 哈希

如何合并散列数组以获取值数组的散列

如何声明 RSpec 中示例之间共享的变量?

如何在控制台中禁用 MongoDB 日志(log)消息?

Sinatra 是多线程的吗?

array.include?多个值

Ruby:module、require和include

就地修改 ruby​​ 哈希(rails strong params)

如何在数组中找到出现次数最多的项目

区分一个Ruby字符串或数组

在 Ruby 中, coerce() 是如何工作的?

Ruby 将 CSV 文件读取为 UTF-8 和/或将 ASCII-8Bit 编码转换为 UTF-8

向实例对象添加方法