Thanks for the more complete explanation. It's always a good idea to post a complete specimen of the input and desired output.
You have a classic "positional grouping" problem (as it happens, I'm talking at the XIME-P conference in Chicago about positional grouping in XQuery later this morning).
Since you're generating the XML, it would be better to generate the proper hierarchical structure in the first place, rather than trying to infer it later.
In XSLT 2.0, the problem is easily tackled using <xsl:for-each-group group-starting-with="if">.
In 1.0, try a search for "XSLT positional grouping". There are two basic approaches:
(a) sibling recursion: apply-templates to all the <if> children. From that template, apply-templates to following-sibling::*[1][not(self::if)], say in mode="next-sibling". From that template, again apply-templates to following-sibling::*[1][not(self::if)], in mode="next-sibling". The recursion terminates automatically when there's no next sibling or when the next sibling is an <if> element.
(b) reduce it to a value-based grouping problem, which you can tackle using the Muenchian grouping method, in which the grouping key is the generate-id() of "." in the case of an <if> element, or of preceding-sibling::if[1] in the case of any other element.
Michael Kay
http://www.saxonica.com/
Author, XSLT Programmer's Reference and XPath 2.0 Programmer's Reference