Searching a list of similar elements for a given value

48 views Asked by At

I have some XML like this:

<Team ...some attributes...>
  <Name>My Team</Name>
  <Player uID="player1">
    <Name>Name</Name>
    <Position>Goalkeeper</Position>
    <Stat Type="first_name">Name</Stat>
    <Stat Type="last_name">Last</Stat>
    <Stat Type="birth_date">bday</Stat>
    <Stat Type="birth_place">bplace</Stat>
    <Stat Type="weight">84</Stat>
    <Stat Type="height">183</Stat>
    <Stat Type="jersey_num">1</Stat>
  </Player>
  <Player uID="player2">
    ...
  </Player>
  ...
</Team>

I want to search for players by jersey_num. I'm using Nokogiri and this code gets me sort of close:

feed.xpath("/Team[@uID='#{team_uid}']//Player/Stat[@Type='jersey_num']")

That returns all the players in a given team, and an array of their jersey number attribute rows, but I want to find a player with a given jersey number, and then pull its uID.

I can do that with ancestor, but first I need this search to yield only one matching player. I realize at the moment I'm not searching for it, but I'm not sure how to search given the Stat Type syntax.

2

There are 2 answers

1
har07 On BEST ANSWER

"... but I want to find a player with a given jersey number, and then pull its uID"

Then the xpath parameter should look about like this :

/Team[@uID='#{team_uid}']//Player[Stat[@Type='jersey_num' and .='#{jersey_num}']]/@uID

or maybe without trailing /@uID to get Player element, and then do further extraction from ruby code. Notice that Stat[....] part in the above xpath filters Stat element by Type attribute value and by value of the element itself.

3
dax On

This works, but I expect there is a better way to go about it:

jersey_number = '23'
players = feed.xpath("/Team[@uID='#{team_uid}']//Player")
player = players.xpath("//Stat[@Type='jersey_num']").detect do |jersery|
  jersery.text == jersey_number
end
player
#=>#<Nokogiri::XML::Element:0x95e8f4 name="Stat" attributes=[#<Nokogiri::XML::Attr:0x9407dc name="Type" value="jersey_num">] children=[#<Nokogiri::XML::Text:0x940048 "23">]>