Have a Ruby REXML element like below:
<a_1>
<Tests>
<test enabled='1'>trans </test>
<test enabled='1'>ac </test>
<test enabled='1'>dc </test>
</Tests>
<Corners>
<corner enabled='0'>default</corner>
<corner enabled='1'>C0 </corner>
</Corners>
</a_1>
I want to find all leaf elements, so the result should be:
<test enabled='1'>trans </test>
<test enabled='1'>ac </test>
<test enabled='1'>dc </test>
<corner enabled='0'>default</corner>
<corner enabled='1'>C0 </corner>
My code is:
require 'rexml/document'
include REXML
def getAllLeaf(xmlElement)
if xmlElement.has_elements?
xmlElement.elements.each {|e|
getAllLeaf(e)
}
else
return xmlElement
end
end
It works fine and did show the right outputs on screen. However, I found I had a problem when I try to save the result to an Array, for this recursive procedure. So I wounder if there is a way to save this output to one array which can be used afterwards?
I struggled out a recursive way to do it, though a little odd, I would like to share it out:
def getAllLeaf(eTop,aTemp=Element.new("LeafElements"))
if eTop.has_elements?
eTop.elements.each {|e|
getAllLeaf(e,aTemp)
}
else
aTemp<< eTop.dup
end
return aTemp
end