Data I'm working with:
(I have this in XML format)
<root>
<!-- level 1 nesting -->
<main name="A" category="group">
<sub name="A.1"></sub>
</main>
<!-- level 1 nesting -->
<main name="B" category="group">
<sub name="B.1"></sub>
</main>
<!-- level 1 nesting -->
<main name="C" category="group">
<sub name="C.1"></sub>
</main>
<!-- level 1 nesting -->
<main name="D" category="group">
<sub name="D.1"></sub>
</main>
<!-- level 2 nesting -->
<main name="E" category="group">
<sub name="E.1" category="group">
<sub name="E.1.1"></sub>
</sub>
</main>
<!-- level n nesting - this is what I need help with -->
<main name="E" category="group">
[...]
</main>
</root>
Desired outcome
- I want to print the above out in ULs and LIs according to their relationships shown above to produce a tree-view.
- The nesting depths of the data I'm working with vary (e.g could be a single item or it could be 100 nesting depth - we don't know)
- I need to write a solution that functionally caters for any level of nesting depth
- Either tag (
mainorsub) with acategoryattribute value of"group"means it has children - The first level tag is always a
main, the rest will besubregardless of nesting depth
What I'm currently trying
def recursiveLoop(group)
str = ""
group.each { |g|
str += "<ul>"
str += "<li>#{g.attribute("name")}"
if g.attribute("category").to_s == "group"
recursiveLoop(g.css("sub"))
else
str += "</li></ul>"
end
}
return str
end
Problem with my solution
After calling itself, the current iteration terminates (as expected) and goes one level deeper. However, I now can't close the <li> nor the <ul> tags as I no longer know where they started.
