2

I have the following simplified XML data and I want to group it by the Category:

<Root>
    <Rows>
        <Row>
            <Column name="Title" Value="Document 1"/>
            <Column name="Category" Value="Category 1"/>
        </Row>
        <Row>
            <Column name="Title" Value="Document 2"/>
            <Column name="Category" Value="Category 2"/>
        </Row>
        <Row>
            <Column name="Title" Value="Document 3"/>
            <Column name="Category" Value="Category 1"/>
        </Row>
        <Row>
            <Column name="Title" Value="Document 4"/>
            <Column name="Category" Value="Category 2"/>
        </Row>
        <Row>
            <Column name="Title" Value="Document 5"/>
            <Column name="Category" Value="Category 3"/>
        </Row>
    </Rows>
</Root>

And I expect the following result:

Category 1

  • Document 1
  • Document 3

Category 2

  • Document 2
  • Document 4

Category 3

  • Document 5

I already tried it with Muenchian grouping because I can only use XSLT 1.0 , but there's no output:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml">
  <xsl:output indent="no" method="html"/>

  <xsl:key name="groups" match="/Rows/Row" use="Column[name='Category']/@Value"/>

  <xsl:template match="/">
    <xsl:apply-templates select="Row[generate-id() = generate-id(key('groups', Column)[1])]"/>
  </xsl:template>

  <xsl:template match="Row">
    <h1>
      <xsl:value-of select="Column[name='Category']/@Value"/>
    </h1>

    <ul>
        <xsl:for-each select="key('groups', Column[name='Category']/@Value)">
            <li>
                <xsl:value-of select="Column[name='Title']/@Value"/>
            </li>
        </xsl:for-each>
    </ul>
  </xsl:template>
</xsl:stylesheet>

I didn't find a solution to group by an attribute where the name is another attribute. Where's my fault, or is there a better solution? Thanks in advance

Claudio P
  • 2,133
  • 3
  • 25
  • 45

1 Answers1

3

Compare:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml">
  <xsl:output indent="no" method="html"/>

  <xsl:key name="groups" match="Row" use="Column[@name='Category']/@Value"/>

  <xsl:template match="/">
    <xsl:apply-templates select="Root/Rows/Row[generate-id() = generate-id(key('groups', Column/@Value)[1])]"/>
  </xsl:template>

  <xsl:template match="Row">
    <h1>
      <xsl:value-of select="Column[@name='Category']/@Value"/>
    </h1>

    <ul>
        <xsl:for-each select="key('groups', Column[@name='Category']/@Value)">
            <li>
                <xsl:value-of select="Column[@name='Title']/@Value"/>
            </li>
        </xsl:for-each>
    </ul>
  </xsl:template>
</xsl:stylesheet>
michael.hor257k
  • 113,275
  • 6
  • 33
  • 51