Ruby 未定义的方法“dig';对于#<;字符串:0x007f91d8579308>;

Ruby 未定义的方法“dig';对于#<;字符串:0x007f91d8579308>;,ruby,rspec,Ruby,Rspec,我想使用dig来获取XML标记值。我试过这个: new_xml_body = Nokogiri::XML(new_xml) new_trx_id = new_xml_body.search('transaction_id').first.text 使用dig: require 'nokogiri' require 'nori' require 'pry' require 'active_model' require 'ruby_dig' new_xml_body = Nokogiri::XML

我想使用dig来获取XML标记值。我试过这个:

new_xml_body = Nokogiri::XML(new_xml)
new_trx_id = new_xml_body.search('transaction_id').first.text
使用dig:

require 'nokogiri'
require 'nori'
require 'pry'
require 'active_model'
require 'ruby_dig'
new_xml_body = Nokogiri::XML(new_xml)
new_trx_id = new_xml_body.dig('transaction_id')
但我得到:

NoMethodError:
       undefined method `dig' for #<String:0x007f91d8579308>
命名错误:
未定义的方法“dig”#

你能为这个问题提出一些解决方案吗?

Nokogiri搜索示例:

require 'nokogiri'

xml_doc  = Nokogiri::XML %q{
<root>
  <aliens>
    <alien>
      <name>Alf</name>
    </alien>
    <human>
      <name>Peter</name>
    </human>
    <alien>
      <name>Bob</name>
    </alien>
  </aliens>
</root>
}

alien_names = xml_doc.xpath('//alien/name/text()')

alien_names.each do |name|
  puts name
end

--output:--
Alf
Bob
对评论的回应

Rails
有一个
Hash#from_xml()
方法。下面是一个使用
dig()
的示例:


新的\u trx\u id
中有什么?你认为dig有什么作用?@ndn它应该存储很长的字符串。如果你需要全面的帮助,请提供。你可以使用nokogiri或nori解析xml?在
new\u xml\u body=Nokogiri::xml(new\u xml)
和最后一行之间有代码吗?我想使用dig来获取xml标记值——为什么不使用Nokogiri呢?毕竟,这就是诺科吉里的目的。ruby_dig docs声明dig是用于哈希或数组的方法,但您对Nokogiri::XML()的返回值调用dig(),该返回值既不是哈希也不是数组,因此出现错误。您不能对Nokogiri::XML()的返回值使用dig(),因此我无法向您展示示例。dig()是一个不相关的方法,它对ruby语言没有什么新的功能。好的,另一种方法:你能告诉我如何将Nokogiri XML转换为哈希吗?然后我将使用.dig。@PeterPenzov,你在使用rails吗?@PeterPenzov,
dig()
我答案底部的示例。
xml_doc  = Nokogiri::XML %q{
<root>
  <aliens>
    <alien planet="Mars">
      <name>Alf</name>
    </alien>
    <human>
      <name>Peter</name>
    </human>
    <alien planet="Alpha Centauri">
      <name>Bob</name>
    </alien>
  </aliens>
</root>
}

alien_names = xml_doc.xpath('//alien[@planet="Alpha Centauri"]/name/text()')

alien_names.each do |name|
  puts name
end

--output:--
Bob
name_tags = xml_doc.css('alien > name')

name_tags.each do |name_tag|
  puts name_tag.text
end

--output:--
Alf
Bob
require 'active_support/core_ext/hash/conversions'
require 'pp'

xml = %q{
<aliens>
  <alien planet="Mars">
    <name>Alf</name>
  </alien>
  <human>
    <name>Peter</name>
  </human>
  <alien planet="Alpha Centauri">
    <name>Bob</name>
  </alien>
</aliens>
}

hash = Hash.from_xml(xml)   #rails method
pp hash
p hash.dig 'aliens', 'human', 'name'
p hash['aliens']['human']['name']

--output:--
{"aliens"=>
  {"alien"=>
    [{"planet"=>"Mars", "name"=>"Alf"},
     {"planet"=>"Alpha Centauri", "name"=>"Bob"}],
   "human"=>{"name"=>"Peter"}}}

"Peter"
"Peter"
doc = Nokogiri:XML(xml)
string = doc.to_s
hash = Hash.from_xml(string)
...