xsl-list
[Top] [All Lists]

this script converts an instance path to an RNG path

2003-03-31 16:02:51
Another XSLT code snippet for anyone using RNG out there. Here's a snippet to convert an instance document path into an XPath-like string that will locate the correct segment of a Relax NG (RNG) grammar.

The input param "fragment" might be something like "/resume/header/contact and then output will be something like "//*[(_at_)name='resume']//*[(_at_)name='header']//*[(_at_)name='contact']/*". You would then call dyn:evaluate() in EXSLT (or whatever equivalent you have) on the resulting string to turn it into a genuine XPath.

Comments welcome as always.

  <!-- Converts an instance path to an RNG path -->
  <xsl:template name="inst2rngPath">
    <xsl:param name="fragment"/>
    <xsl:choose>
<xsl:when test="starts-with($fragment, '/')"> <!-- strip beginning / -->
        <xsl:call-template name="inst2rngPath">
<xsl:with-param name="fragment" select="substring-after($fragment, '/')"/>
        </xsl:call-template>
      </xsl:when><xsl:otherwise>
        <xsl:text>//*[(_at_)name='</xsl:text>
        <xsl:choose><xsl:when test="substring-before($fragment, '/')">
            <xsl:value-of select="substring-before($fragment, '/')"/>
          </xsl:when><xsl:otherwise>
            <xsl:value-of select="$fragment"/>
        </xsl:otherwise></xsl:choose>
        <xsl:text>']</xsl:text>
        <xsl:choose>
<xsl:when test="contains($fragment, '/')"> <!-- recursive step -->
            <xsl:call-template name="inst2rngPath">
<xsl:with-param name="fragment" select="substring-after($fragment, '/')"/>
            </xsl:call-template>
          </xsl:when><xsl:otherwise>  <!-- default step -->
            <xsl:text>/*</xsl:text>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

simon
--
www.simonwoodside.com -- 99% Devil, 1% Angel


XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list



<Prev in Thread] Current Thread [Next in Thread>