使用 nokogiri 浏览 XML 文档

Navigating an XML doc with nokogiri

我有一个简单的 XML 文档,如下所示:

<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>

我试图遍历每个玩家对象并单独访问每个子节点及其各自的值。我正在尝试如下操作:

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

虽然我不完全确定如何在此处访问 lineup 的各个子元素。使用 nokogiri 执行此操作的最佳方法是什么?

尝试使用 XPath /Lineup/Player/* 检查每个 "Player" 节点的每个子元素:

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...

或者,您可以 select 每个 "Player" 并迭代其 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