我正在使用Nokogiri来解析我在创建用户后从咆哮引擎获取的XML数据。 XML如下所示:
<roar tick="135098427907">
<facebook>
<create_oauth status="ok">
<auth_token>14802206136746256007</auth_token>
<player_id>8957881063899628798</player_id>
</create_oauth>
</facebook>
</roar>
我对Nokogiri完全不熟悉。如何获得status
,auth_token
和player_id
的价值?
答案 0 :(得分:2)
str = "<roar ......"
doc = Nokogiri.XML(str)
puts doc.xpath('//create_oauth/@status') # => ok
puts doc.xpath('//auth_token').text # => 148....
# player_id is the same as auth_token
从w3schools了解一些好的xpath是一个好主意。
答案 1 :(得分:2)
这个怎么样
h1 = Nokogiri::XML.parse %{
<roar tick="135098427907">
<facebook>
<create_oauth status="ok">
<auth_token>14802206136746256007</auth_token>
<player_id>8957881063899628798</player_id>
</create_oauth>
</facebook>
</roar>
}
h1.xpath("//facebook/create_oauth/auth_token").text()
h1.xpath("//facebook/create_oauth/player_id").text()
答案 2 :(得分:2)
您可以使用Nori gem。它是一个xml到哈希转换器,在ruby中它非常方便访问哈希
require 'nori'
Nori.parser = :nokogiri
xml = "<roar tick='135098427907'>
<facebook>
<create_oauth status='ok'>
<auth_token>14802206136746256007</auth_token>
<player_id>8957881063899628798</player_id>
</create_oauth>
</facebook>
</roar>"
hash = Nori.parse(xml)
create_oauth = hash["roar"]["facebook"]["create_oauth"]
puts create_oauth["auth_token"] # 14802206136746256007
puts create_oauth["@status"] # ok
puts create_oauth["player_id"] # 8957881063899628798