tags:

views:

30

answers:

1

I need to take this xml…

<root>
   <item id=’1’ parent_id=’0’>ONE</item>
   <item id=’2’ parent_id=’1’>TWO</item>
   <item id=’3’ parent_id=’1’>THREE</item>
   <item id=’4’ parent_id=’2’>FOUR</item>
   <item id=’5’ parent_id=’0’>FIVE</item>
</root>

And produce this xhtml…

<div class=’parent’>ONE</div>
<div class=’child’>
   <div class=’parent’>TWO</div>
   <div class=’child’>
      <div class=’parent’>FOUR</div>
   </div>
   <div class=’parent’>THREE</div>
</div>
<div class=’parent’>FIVE</div>

I get how to collect the child nodes and put them under their parent, but I can’t grasp how to then skip over considering them as parents if I have already used them as children.

A: 

Tested the following, which appears to work

Apply all items at the root with parent_id = 0, then recursively iterate for any children..

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;

<xsl:template match="/">
  <xsl:apply-templates select="root/item[@parent_id='0']"/>
</xsl:template>


<xsl:template match="item">
  <div class="parent"><xsl:value-of select="."/></div>
  <xsl:if test="count(../item[@parent_id=current()/@id]) != 0">
    <div class="child">
      <xsl:apply-templates select="../item[@parent_id=current()/@id]"/>
    </div>
  </xsl:if>
</xsl:template>
scunliffe