Jorge Flores
Jorge Flores

Reputation: 43

How to concanenate an incremental id to an existing value

I have the following xml:

enter image description here

I would like to concatenate the postioName column an incremental ID, for example:

enter image description here

So far I have managed to achieve something similar using the function : "generate-id()" but the result in not quite what I expect:

enter image description here

Is there a better way to achieve this?

The way I am doing it is:

<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
	<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
	<xsl:strip-space elements="*"/>
	<!-- Identity transform -->
	<xsl:template match="@* | node()">
		<xsl:copy>
			<xsl:apply-templates select="@* | node()"/>
		</xsl:copy>
	</xsl:template>
	<xsl:template match="/IDS/records/positionName">
		<xsl:copy>
			<xsl:value-of select="../positionName"/>
			<xsl:value-of select="'_'"/>
			<xsl:value-of select="generate-id()"/>
		</xsl:copy>
	</xsl:template>
</xsl:stylesheet>

<IDS>
	<records>
		<positionId>a</positionId>
		<positionName>ID</positionName>
		<maturityDate>20251217</maturityDate>
	</records>
	<records>
		<positionId>b</positionId>
		<positionName>ID</positionName>
		<maturityDate>20251217</maturityDate>
	</records>
	<records>
		<positionId>c</positionId>
		<positionName>ID</positionName>
		<maturityDate>20251217</maturityDate>
	</records>
</IDS>

Upvotes: 1

Views: 26

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167446

Use <xsl:number count="records"/> to generate the number, <xsl:value-of select=". || '_'"/><xsl:number count="records"/>, so a complete XSLT 3 stylesheet is

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template match="/IDS/records/positionName">
      <xsl:copy>
        <xsl:value-of select=". || '_'"/>
        <xsl:number count="records"/> 
      </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/ncdD7m5/1

Upvotes: 2

Related Questions