Adding ID and ParentID Attributes to XML with XSLT

by Administrator 17. September 2013 10:10
When transforming XML between applications,
sometimes it's necessary to explicitly disambiguate node paths.

This stylesheet adds id and parentid attributes:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
  <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>

Note that this stylesheet works well as V1 XSLT as well.

Tags:

Log in
Privacy Policy Terms and Conditions Copyright Relational Development