如何使用Nokogiri将XML添加到数组中?

时间:2014-03-05 21:22:19

标签: ruby xml nokogiri

我将此作为我的XML:

<systems>
<system number="2" >
<lists>
<list critical="user" access="remote"></list>
<list critical="root" access="local"></list>
</lists>
<os system="linux" basebox="AddBaseBox" ></os>
<networks>
<network name="homeonly" ></network>
<network name="homeonly2"></network>
</networks>
</system>
</systems>

我想将它们添加到数组中,所以我写了这个:

require 'nokogiri'

doc = Nokogiri::XML(File.open("boxesconfig.xml"))

doc.search('//systems/system').each do |system|
    list = []
    networks = []
    systemNumber  = system.at('@number').text
    os  = system.at('//os/@system').text
    base = system.at('//os/@basebox').text

    list << { "critical" => system.at('//lists/list/@critical').text, "access" => system.at('//lists/list/@access').text}
    networks << { "network" => system.at('//networks/network/@name').text}
    puts list
    puts systemNumber
    puts os
    puts networks    
end

我收到的输出是:

{"critical"=>"user", "access"=>"remote"}
2
linux
{"network"=>"homeonly"}

我希望在阵列中显示多个列表和多个网络。我做错了什么?

我想要的输出是:

{"critical"=>"user", "access"=>"remote"}
{"root"=>"user", "access"=>"local"}
2
linux
{"network"=>"homeonly"}
{"network"=>"homeonly2"}

1 个答案:

答案 0 :(得分:1)

Nokogiri允许您使用CSS选择器访问XML。当你的选择器匹配多个东西时,Nokogiri会返回一系列的东西。在这里,我们使用Ruby的Array#collect方法根据块返回的内容返回一个新的项目数组:

lists = system.css('lists list').collect do |list| 
  { 'critical' => list['critical'], 'access' => list['access'] } 
end

networks = system.css('networks network').collect do |network| 
  { 'network' => network['name'] } 
end

这应该可以为您提供所需的输出。