Skip to content Skip to sidebar Skip to footer

XSL For Xml: Inserting Specific Classes Using XSL

I have another XSLT question which follows on from the question I asked last week. XSL for Xml to table transformation for two rows and many columns. The challenges is to insert di

Solution 1:

Use this XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="my">
  <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>

  <xsl:key name="k" match="page" use="@section"/>

  <xsl:param name="short-name" select="true()"/>
  <!-- Change param to false()-->

  <my:data>
    <club name="Arsenal">AFC</club>
    <club name="Chelsea">CFC</club>
    <club name="ManUnited">MUFC</club>
    <club name="ManCity">MCFC</club>
  </my:data>

  <xsl:template match="/root">
    <table>
      <tr>
        <xsl:apply-templates select="page[generate-id() = generate-id(key('k', @section))]"/>
      </tr>
      <tr>
        <xsl:apply-templates select="page[generate-id() = generate-id(key('k', @section))]" mode="page"/>
      </tr>
    </table>
  </xsl:template>

  <xsl:template match="page">
    <xsl:variable name="class">
      <xsl:choose>
        <xsl:when test="$short-name">
          <xsl:value-of select="document('')/*/*/club[@name = current()/@section]"/>
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="@section"/>
        </xsl:otherwise>
      </xsl:choose>

    </xsl:variable>

    <td class="{$class}">
      <xsl:value-of select="."/>
    </td>
    <td></td>
  </xsl:template>

  <xsl:template match="page" mode="page">
    <td>
      <xsl:value-of select="@number"/>
    </td>
    <td>
      <xsl:value-of select="key('k', @section)[last()]/@number"/>
    </td>
  </xsl:template>

</xsl:stylesheet>

Depending on parameter $short-name it renders your 1 desired XML or 2.


Post a Comment for "XSL For Xml: Inserting Specific Classes Using XSL"