开发者

Manipulating XML files in ruby with XmlSimple

I've got a complex XML file, and I want to extract a content of a specific tag from it. I use a ruby script with XmlSimple gem. I retrieve an XML file with HTTP request, then strip all the unnecessary tags and pull out necessary info. That's the script itself:

data = XmlSimple.xml_in(response.body)
hash_1 = Hash[*data['results']]


def find_value(hash, value)
  hash.each do |key, val|
    if val[0].kind_of? Hash then
      find_value(val[0], value)
    else
      if key.to_s.eql? va开发者_开发问答lue
         puts val
      end
    end
  end
end

hash_1['book'].each do |arg|
  find_value(arg, "title")
  puts("\n")
end

The problem is, that when I change replace puts val with return val, and then call find_value method with puts find_value (arg, "title"), i get the whole contents of hash_1[book] on the screen.

How to correct the find_value method?


A "complex XML file" and XmlSimple don't mix. Your task would be solved a lot easier with Nokogiri, and be faster as well:

require 'nokogiri'
doc = Nokogiri::XML(response.body)

puts doc.xpath('//book/title/text()')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜