使用nokogiri导航XML文档

时间:2015-04-06 19:51:28

标签: ruby xml 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最好的方法是什么?

1 个答案:

答案 0 :(得分:2)

尝试使用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...

或者,您可以选择每个“播放器”并迭代其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