【问题标题】:ruby converting nokogiri xml to hashruby 将 nokogiri xml 转换为哈希
【发布时间】:2016-08-26 06:31:18
【问题描述】:

我正在尝试将带有 Nokogiri 的 XML 转换为哈希:

<eveapi version="2">
  <currentTime>2016-05-01 11:38:14</currentTime>
  <result>
    <characterID>93898118</characterID>
    <characterName>Ghitzarai</characterName>
    <race>Minmatar</race>
    <bloodlineID>4</bloodlineID>
    <bloodline>Brutor</bloodline>
    <ancestryID>24</ancestryID>
    <ancestry>Slave Child</ancestry>
    <corporationID>98012663</corporationID>
    <corporation>Dry Atomic Fusion</corporation>
  </result>
</eveapi>

# asume xml is the above XML
hash = {}
xml.xpath('//result').each do |row|
  hash[get_node_name:] = row.content
end

现在row.name 将不起作用,因为它只返回一次result

如何从子节点获取正确的名称?

【问题讨论】:

  • 我刚刚注意到 xml.xpath('//result') 的长度只有 1。所以问题也出现了如何遍历孩子
  • 使用...xpath('//result/*')... ?
  • 啊,是的。非常感谢!
  • 将我的评论转换为简要说明 XPath 究竟做了什么
  • 另请参阅 my answerConvert a Nokogiri document to a Ruby Hash,了解将任何 Nokogiri 文档序列化为哈希的小而强大的实现。

标签: ruby xml nokogiri


【解决方案1】:

“现在row.name 将无法工作,因为它只返回一次结果。如何从子节点获取正确的名称?”

result 之后添加/* 以获得&lt;result&gt;所有 个子元素,无论子元素名称如何:

xml.xpath('//result/*').each do |row|

【讨论】:

    猜你喜欢
    • 2010-11-16
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    相关资源
    最近更新 更多