2013-01-24 39 views
1

我有一个看起来像这样的XML文档:如何遍历XML儿童使用Ruby REXML节点

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

<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如下循环

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

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

见ms像我尝试的一切,我会得到所有的检查,而不仅仅是每个许可证的检查。

对此提出建议?

回答

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树下有多深。

希望这会有所帮助! :)