Shadow Gorilla
Shadow Gorilla

Reputation: 1

How to add ID\ParentID with XSLT

Given an xml tree example:

<root>
  <child></child>
  <child>
    <child></child>
  </child>
</root>

can someone help me with a stylesheet that will add id and parentid attributes:

<root id="1" parentID="">
  <child id="2" parentID="1"></child>
  <child id="3" parentID="1">
    <child id="4" parentID="3"></child>
  </child>
</root>

Upvotes: 0

Views: 298

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167436

Use

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

<xsl:template match="*">
  <xsl:copy>
    <xsl:attribute name="id">
      <xsl:apply-templates select="." mode="number"/>
    </xsl:attribute>
    <xsl:attribute name="parentId">
      <xsl:apply-templates select="parent::*" mode="number"/>
    </xsl:attribute>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="*" mode="number">
  <xsl:number level="any" count="*"/>
</xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions