Search code examples
xmlxsltxpathxslt-1.0xslt-grouping

Nested grouping based on parent field using XSLT


This is a sample of the raw XML I'm working with:

<dsQueryResponse>
  <Rows>
    <Row Title="Animal" Parent="" />
    <Row Title="Mammal" Parent="Animal" />
    <Row Title="Lion" Parent="Mammal" />
    <Row Title="Plant" Parent="" />
    <Row Title="Elephant" Parent="Mammal" />
  </Rows>
</dsQueryResponse>

Using XSLT, how do I get the output to be a nested UL like:

<ul>
  <li>
    Animal
    <ul>
      <li>
        Mammal
        <ul>
          <li>Elephant</li>
          <li>Lion</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Plant</li>
</ul>

I'm only "okay" with XSLT and can only do simple sorting, and I know I can do this easily through JavaScript/jQuery, but I'd rather use XSLT for this.


Solution

  • Try this XSLT:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="xml" indent="yes"/>
    
      <xsl:template match="/">
        <ul>
          <xsl:apply-templates select="//Row[@Parent = '']"/>
        </ul>
      </xsl:template>
    
      <xsl:template match="Row">
        <li>
          <xsl:value-of select="@Title"/>
    
          <xsl:if test="../Row[@Parent = current()/@Title]">
            <ul>
              <xsl:apply-templates select="../Row[@Parent = current()/@Title]"/>
            </ul>
          </xsl:if>
        </li>
      </xsl:template>
    </xsl:stylesheet>
    

    Output:

    <ul>
      <li>
        Animal<ul>
          <li>
            Mammal<ul>
              <li>Lion</li>
              <li>Elephant</li>
            </ul>
          </li>
        </ul>
      </li>
      <li>Plant</li>
    </ul>