2013-01-24 40 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樹下有多深。

希望這會有所幫助! :)