Home > OS >  insert id iteration in child with XSLT
insert id iteration in child with XSLT

Time:10-15

I want to insert an id on the "id" child element of "person" element.

But I don't see how I should do it.

Can you help me ?

source xml;

<persons>
<person>
    <id></id>
    <name>Lisa</name>
</person>
<person>
    <id></id>
    <name>Robin</name>
</person>
<person>
    <id></id>
    <name>Alex</name>
</person>

xml which I want;

<persons>
<person>
    <id>1</id>
    <name>Lisa</name>
</person>
<person>
    <id>2</id>
    <name>Robin</name>
</person>
<person>
    <id>3</id>
    <name>Alex</name>
</person>

thank you

CodePudding user response:

The xsl:number instruction in XSLT is an easy way to generate a running number you can use as an identifier. In this example I've used xsl:number to generate a number that reflects the position of the parent (i.e. ..) person element within the outer persons element.

Input:

<persons>
  <person>
    <id></id>
    <name>Lisa</name>
  </person>
  <person>
    <id></id>
    <name>Robin</name>
  </person>
  <person>
    <id></id>
    <name>Alex</name>
  </person>
</persons>

Stylesheet:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">

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

  <xsl:template match="person/id">
    <id><xsl:number select=".."/></id>
  </xsl:template>
  
</xsl:stylesheet>

Result:

<persons>
  <person>
    <id>1</id>
    <name>Lisa</name>
  </person>
  <person>
    <id>2</id>
    <name>Robin</name>
  </person>
  <person>
    <id>3</id>
    <name>Alex</name>
  </person>
</persons>

CodePudding user response:

excellent. Thanks.

... and in XSLT v2.0 :

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

        <xsl:template match="node() | @*">
            <xsl:copy>
                <xsl:apply-templates select="node() | @*"/>
            </xsl:copy>
        </xsl:template>

        <xsl:template match="person/id">
            <xsl:element name="id">
                <xsl:number count="person"/>
            </xsl:element>
        </xsl:template>

</xsl:stylesheet>
  • Related