randombits
randombits

Reputation: 48440

Navigating an XML doc with nokogiri

I have a simple XML doc that looks like the following:

<Lineup>
 <Player>
    <GameID>20150010</GameID>
    <GameDate>2015-04-06T00:00:00-04:00</GameDate>
    <DH>0</DH>
    <TeamId>16</TeamId>
    <PlayerId>458913</PlayerId>
    <LineupPosition>1</LineupPosition>
    <DefensivePosition>8</DefensivePosition>
  </Player>
  <Player>
    <GameID>20150010</GameID>
    <GameDate>2015-04-06T00:00:00-04:00</GameDate>
    <DH>0</DH>
    <TeamId>16</TeamId>
    <PlayerId>607054</PlayerId>
    <LineupPosition>2</LineupPosition>
    <DefensivePosition>4</DefensivePosition>
  </Player>
  <Player>
    <GameID>20150010</GameID>
    <GameDate>2015-04-06T00:00:00-04:00</GameDate>
    <DH>0</DH>
    <TeamId>16</TeamId>
    <PlayerId>455976</PlayerId>
    <LineupPosition>3</LineupPosition>
    <DefensivePosition>9</DefensivePosition>
  </Player>
</Lineup>

I'm attempting to loop through each player object and individually access every single child node and its respective value. I'm trying something like the following:

xml_doc.xpath("//Lineup/Player").each do |lineup|
  puts "lineup: #{lineup.inspect}"
end

I'm not entirely sure how to access individual children elements of lineup here though. What's the best way to do this using nokogiri?

Upvotes: 2

Views: 288

Answers (1)

maerics
maerics

Reputation: 156404

Try using the XPath /Lineup/Player/* to inspect each child element of each "Player" node:

doc = Nokogiri::XML(File.read('my.xml'))
doc.xpath('/Lineup/Player/*').each do |node|
  puts "#{node.name}: #{node.text}"
end
# GameID: 20150010
# GameDate: 2015-04-06T00:00:00-04:00
# DH: 0
# ...etc...

Alternatively, you can select each "Player" and iterate over its element children (by using #elements or #element_children):

doc.xpath('/Lineup/Player').each do |player|
  puts "-- NEXT PLAYER --"
  player.elements.each do |node|
    puts "#{node.name}: #{node.text}"
  end
end

Upvotes: 2

Related Questions