Get XPath of an XML node

Get XPath of an XML node

There are lots of XSL templates out there that get a human readable path to a node. But none of them cover the case when there are more than one node of the same element at the same level.

Please find below the code that get XPath of an XML node:

<xsl:stylesheet version="1.0" xmlns:xsl="">
  <xsl:output indent="yes">
    <xsl:template match="@*|node()">
        <xsl:tagibute name="position">
          <xsl:call-template name="xpath.position">
            <xsl:apply-templates select="@*|node()"></xsl:apply-templates>
    <xsl:template name="xpath.position">
     <xsl:param name="node" select="."></xsl:param>
     <xsl:param name="path" select="''"></xsl:param>
     <xsl:variable name="next.path">
      <xsl:value-of select="$node/count(preceding-sibling::*)+1">
       <xsl:if test="$path != ''">/</xsl:if>
       <xsl:value-of select="$path"></xsl:value-of>
    <xsl:when test="$node/parent::*">
      <xsl:call-template name="xpath.position">
        <xsl:with-param name="node" select="$node/parent::*"></xsl:with-param>
          <xsl:with-param name="path" select="$next.path"></xsl:with-param>
        <xsl:value-of select="$next.path"></xsl:value-of>

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *