1

我有一个看起来像这样的 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'}]}]

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

建议?

4

1 回答 1

1

I had the same problem. I tried this on my code and it worked. (I'm using yours though)

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

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

@myInspectionAmounts.push(amount)

I'm sure you can put that in a loop to get all the inspections, but this is the method i tried and I got all the values i needed regardless of how deep they were down the xml tree.

Hope this helps! :)

于 2013-03-07T20:28:51.493 回答