Friday, February 1, 2008

How to Get XPath to an XML Node

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

In order to solve this problem you can use the following code:

<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>


No comments:

Post a Comment

Linked In Profile

Follow me

Follow by Email

About Me

My photo
Expert Senior Software Developer