Ruby: How do I get attribute values from XML with Nokogiri?

谁说胖子不能爱 提交于 2020-01-14 18:43:51

问题


How to get the value of the message value ("ready to use")?

<?xml version="1.0" encoding="UTF-8"?>
<response status="ok" permission_level="admin" message="ready to use" cached="0">
<title>kit</title>
</response>

Thanks


回答1:


require 'rubygems'
require 'nokogiri'

string = %Q{
  <?xml version="1.0" encoding="UTF-8"?>
  <response status="ok" permission_level="admin" message="ready to use" cached="0">
  <title>kit</title>
  </response>
}

doc = Nokogiri::XML(string)
doc.css("response").each do |response_node|
  puts response_node["message"]
end

save and run this ruby file, you will get result:

#=> ready to use



回答2:


You subscript them.

doc = Nokogiri::HTML(open('http://google.com'))
doc.css('img:first').first['alt']
=> "Google"


来源:https://stackoverflow.com/questions/10119438/ruby-how-do-i-get-attribute-values-from-xml-with-nokogiri

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!