That said, I wonder whether that problem can be solved more flexible using XSLT, a language that makes my brain freeze whenever I see a template. But would XSLT in principle be a more powerful way of formatting the tree?
If XSLT makes your brain freeze, there is also XQuery, which is a functional language that has a more procedural look to it ( not encoded as XML ), but include XPath and XPath functions, so is very good at traversing the tree. ( And current version in Saxon,BaseX,eXist all support Path 3.x, where lxml is XPATH 1.0 (I believe)).
However, the XSLT push style of template processing is very handy for documents where the content is very variable and unpredictable, which in a procedural language would usually require a lot of case statements, or else implementing your own template expander manually.
— Steve.