Sunday 6 May 2012

Interesting use of position()

INPUT:-


<?xml version="1.0" encoding="UTF-8"?>
<aaa>
  <bbb>A</bbb>
  <bbb>B</bbb>
  <bbb>C</bbb>
  <bbb>D</bbb>
</aaa>


Output:-
<xxx>

  <zzz>1. A</zzz>
  <zzz>2. B</zzz>
  <zzz>3. C</zzz>
  <zzz>4. D</zzz>
</xxx>
<yyy>
  <zzz>1. C</zzz>
  <zzz>2. D</zzz>
</yyy>


XSLT:-

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">

  <xsl:template match="/">
    <xsl:apply-templates select="aaa"/>
  </xsl:template>

  <xsl:template match="aaa">
    <xsl:element name="xxx">
      <xsl:apply-templates select="bbb"/>
    </xsl:element>
    <xsl:element name="yyy">
      <xsl:apply-templates select="bbb[position() > 2]"/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="bbb">
    <xsl:element name="zzz">
      <xsl:value-of select="concat(position(),'. ')"/>
      <!--<xsl:number count="bbb" level="single"/>-->
      <xsl:value-of select="."/>
    </xsl:element>
  </xsl:template>
</xsl:stylesheet>

Note:- Notice red color number call “bbb[position() >2” create a sequence of two bbb element so is the output.

Use <xsl:number count="bbb" level="single"/> instead of position for the below output:-

<xxx>
    <zzz>1A</zzz>
    <zzz>2B</zzz>
    <zzz>3C</zzz>
    <zzz>4D</zzz>
  </xxx>
  <yyy>
    <zzz>3C</zzz>
    <zzz>4D</zzz>
  </yyy>


No comments: