根据属性值选择特定属性

时间:2015-09-10 03:06:11

标签: ruby-on-rails ruby xml xpath nokogiri

我有这种格式的XML文件:

 <league country="argentina" name="Argentina: Torneo Federal A - Winners Stage" cup="False" id="2909" sub_id="29094">
  <match alternate_id="4187269" alternate_id_2="4394549" date="14.08.2015" id="4304775" static_id="14081523515562337775" status="FT" time="18:00">
    <home goals="2" id="2351556" name="Club Atletico Mitre"></home>
    <away goals="1" id="2337775" name="Chaco For Ever"></away>
    <events>
    <event assist="" assistid="" id="22958994" minute="32" player="Juan Pablo Villafane" playerid="" result="[1 - 0]" team="home" type="goal"></event>
    <event assist="" assistid="" id="22958995" minute="48" player="Aldo Visconti" playerid="" result="[1 - 1]" team="away" type="goal"></event>
    <event assist="" assistid="" id="22958996" minute="90" player="Emanuel Lazzarini" playerid="" result="[2 - 1]" team="home" type="goal"></event>
    </events>
    <ht score="[1-0]"></ht>
    <ft score="[2-1]"></ft>
    </match></league><league country="argentina" name="Argentina: Torneo Federal A - Losers Stage" cup="False" id="2909" sub_id="29095"><match alternate_id="4178253" alternate_id_2="4410516" date="14.08.2015" id="4295774" static_id="14081523557572337894" status="FT" time="18:00">
    <home goals="2" id="2355757" name="Velez de San Ramon"></home>
    <away goals="1" id="2337894" name="Sportivo Patria"></away>
    <events>
    <event assist="" assistid="" id="23118664" minute="11" player="Diego Suarez" playerid="" result="[1 - 0]" team="home" type="goal"></event>
    <event assist="" assistid="" id="23118665" minute="64" player="Luis Leguizamon" playerid="" result="[2 - 0]" team="home" type="goal"></event>
    <event assist="" assistid="" id="23118666" minute="67" player="Rodrigo Ramirez (o.g.)" playerid="" result="[2 - 1]" team="away" type="goal"></event>
    </events>
    <ht score="[1-0]"></ht>
    <ft score="[2-1]"></ft>

这是我的控制者:

xml = Nokogiri::XML(f) 

  path = "//match[@static_id='user.matchid']"
  @country = xml.xpath(path)

如何根据属性"result" = [1-0][0-1]的值条件获取团队名称?

1 个答案:

答案 0 :(得分:0)

我做的事情如下:

require 'nokogiri'

doc = Nokogiri::XML(<<EOT)
  <xml>
     <league>
      <match>
        <events>
          <event player="Juan Pablo Villafane" result="[1 - 0]" team="home"></event>
          <event player="Aldo Visconti" result="[1 - 1]" team="away"></event>
        </events>
        <events>
          <event player="Diego Suarez" result="[1 - 0]" team="home"></event>
          <event player="Luis Leguizamon" result="[2 - 0]" team="home"></event>
        </events>
      </match>
    </league>
  </xml>
EOT

doc.search('//event[contains(@result, "[1 - 0]") or contains(@result, "[0 - 1]")]/@team').map(&:text)
# => ["home", "home"]