如何使用Ruby REXML循环遍历XML子节点

时间:2013-01-24 19:55:34

标签: ruby rexml

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

<permit>
  <id>1</id>
  <inspection>
    <amount>100</amount>
    <type>pool</type>  
  </inspection>
  <inspection>
    <amount>400</amount>
    <type>pluminbing</type>  
  </inspection>
</permit>
<permit>
  <id>2</id>
  <inspection>
    <amount>1500</amount>
    <type>roof</type>  
  </inspection>
  <inspection>
    <amount>1700</amount>
    <type>building</type>  
  </inspection>
</permit>

我知道我可以循环通过许可证并输出ID如下:

 REXML::XPath.each(doc, '//permit') do |permit|
   permit_hash = {:id => permit.elements['id'].text}
 end

但我似乎无法遍历每个许可证的检查并最终得到一个数组输出,例如:

 permits = [{:id => 1, :inspections => [{:amount => 100, :type => 'pool'}, {:amount =>   400, :type => 'plumbing'}]}, {:id => 2, :inspections => [{:amount => 1500, :type => 'roof'}, {:amount => 1700, :type => 'building'}]}]

似乎我尝试的一切都得到了所有的检查,而不仅仅是每个许可证的检查。

建议?

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题。我在我的代码上尝试了这个并且它有效。 (虽然我正在使用你的)

//create a new array
@myInspectionsAmounts=Array.new

//get the amount from the inspection
amount = permits.elements['inspection'].elements['amount'].text

@myInspectionAmounts.push(amount)

我确信你可以把它放在循环中以获得所有的检查,但这是我尝试的方法,我得到了我需要的所有值,无论它们在xml树下有多深。

希望这有帮助! :)