I have an xml document, that has a list of categories:
<categories> <category id='1' parent='0'>Configurations</category> <category id='11' parent='13'>LCD Monitor</category> <category id='12' parent='13'>CRT Monitor</category> <category id='13' parent='1''>Monitors</category> <category id='123' parent='122'>Printer</category> ... </categories>
And a list of products:
<products> <product> ... <category>12</category> ... </product> ... </products>
If product’s category is equal to 12, then it should be transformed to ‘Configurations/Monitors/CRT Monitor’ (take category 12, then it’s parent (13), etc.). If parent is 0, stop.
Is there an elegant way to do this using a XSL Transformation?
I don’t know whether this would be considered elegant, but with this input:
This XSLT:
Will give you this output:
The paths still have an extra trailing slash, you’d need another little bit of conditional XSLT to make the slash only get emitted when you aren’t at the first level.
It is vital that you category hierarchy is correct, otherwise your transform can easily get into an endless loop that will only stop when it runs out of memory. If I was implementing something like this in a real system I’d be tempted to add a parameter to the catWalk template that incremented on each call and add it to the test so it stopped looping after 10 calls whether or not the parent had been found.