使用nokogiri解析我想要的数据的XML

时间:2015-06-03 14:58:24

标签: ruby-on-rails ruby xml nokogiri

我正在使用Nokogiri gem来解析XML数据,但在获取我想要的数据时遇到了问题。

这是我的控制器代码:

      def matches

      f = File.open("england.xml")
      doc = Nokogiri::XML(f)

      @away =  doc.xpath("//league/match/odds/type[@name='1x2']/bookmaker[@id='821']")
      @homeaway = doc.xpath("//league/match/odds/type[@name='Home/Away']/bookmaker[@id='781']")
      @overunder = doc.xpath("//league/match/odds/type[@name='Over/Under']/bookmaker[@id='781']")
      @handicap = doc.xpath("//league/match/odds/type[@name='Handicap']/bookmaker[@id='781']")

这是我遇到问题的XML Feed的一部分:

  <league>
   <match>
    <odds>
     <type name="Handicap">
      <bookmaker id="781" name="Bet365">
       <handicap name="-1.75">
        <odd name="1" value="2.15">
       </handicap>
       <handicap name="+1.75">
        <odd name="2" value="1.68">
       </handicap>
       <handicap name="-1.50">
        <odd name="1" value="1.95">
       </handicap>
       <handicap name="+1.50">
        <odd name="2" value="1.95">
       </handicap>
      </bookmaker>
     </type>
     </odds>
    </match>
   </league>

这是我的观点:

 <table id="tableID">
   <td>Home
    <td>Away</td>
    <td></td>
    <td></td>
   </td>
   <% @handicap.each do |k| %>
   <tr>
   <td><%= k.parent.parent.parent.children.attr("name") %></td>
   <td><%= k.parent.parent.parent.children[1].attr("name") %></td>
   <td><%= k.children[2].attr("name") %> | <%=          k.children[2].children.attr("value") %></td>
   <td> <%= k.children[3].attr("name") %> | <%= k.children[3].children.attr("value") %></td>
   </tr>
   <% end %>
   </table>

假设有很多差点,我想总是显示最接近2.00的差点奇数值,我该怎么做?请帮忙。谢谢!

1 个答案:

答案 0 :(得分:0)

这里有一些代码可以从XML中提取值。您必须弄清楚如何确定数组中哪个条目最接近您的目标:

require 'nokogiri'

doc = Nokogiri::XML(<<EOT)
<league>
 <match>
  <odds>
   <type name="Handicap">
    <bookmaker id="781" name="Bet365">
     <handicap name="-1.75">
      <odd name="1" value="2.15">
     </handicap>
     <handicap name="+1.75">
      <odd name="2" value="1.68">
     </handicap>
     <handicap name="-1.50">
      <odd name="1" value="1.95">
     </handicap>
     <handicap name="+1.50">
      <odd name="2" value="1.95">
     </handicap>
    </bookmaker>
   </type>
   </odds>
  </match>
</league>
EOT

handicap_odd = doc.search('type bookmaker[id="781"] handicap').map{ |handicap| 
  odd = handicap.at('odd')
  [
    handicap['name'], 
    odd['name'], 
    odd['value'].to_f
  ] 
}

运行后,handicap_odd包含一系列handicap个名称和相关的odd值:

handicap_odd
# => [["-1.75", "1", 2.15],
#     ["+1.75", "2", 1.68],
#     ["-1.50", "1", 1.95],
#     ["+1.50", "2", 1.95]]

您需要弄清楚searchat做了什么以及他们为何与众不同。

请注意,我使用CSS而不是XPath作为选择器,这是为了便于阅读。