Re: [xsl] JSON-encoding strings in XSLT 2.0

Subject: Re: [xsl] JSON-encoding strings in XSLT 2.0
From: David Cramer <david@xxxxxxxxxxxx>
Date: Tue, 10 Dec 2013 09:29:07 -0600
On 11/06/2013 09:37 AM, Michael Kay wrote:
> I must admit I wasn't really thinking in terms of performance. I guess 
> for performance it would be better to write
> 
> <xsl:variable name="json-escapes">
>  <esc j="\\" x="\"/>
>  <esc j="\n" x="&10;"/>
>  ...
> </xsl:variable>
> 
> <xsl:key name="json-escapes" match="esc" use="@j"/>
> 
> <xsl:analyze-string select="$in" regex="\\|\'|\n|....">
>  <xsl:matching-substring>
>   <xsl:value-of select="key('json-escapes", ., $json-escapes)/@x"/>
>  </xsl:matching-substring>
>  <xsl:non-matching-substring>
>    <xsl:value-of select="."/>
>  </xsl:non-matching-substring>
> </xsl;analyze-string>
> 
> Michael Kay
> Saxonica

Very helpful. thanks! For reference, I made a couple of small adjustments (e.g. reversing x and j 
in the key):

<xsl:variable name="regexp">\\|\n|\r|\t|"|/</xsl:variable>
<xsl:variable name="json-escapes">
    <esc j="\\" x="\"/>
    <esc j="\n" x="&#10;"/>
    <esc j="\&#34;" x="&#34;"/><!-- " -->
    <esc j="\t" x="&#09;"/>
    <esc j="\r" x="&#13;"/>     
    <esc j="\/"  x="/"/>
</xsl:variable>

<!-- use * to avoid namespace problems -->
<xsl:key name="json-escapes" match="*" use="@x"/>

<xsl:template match="text()" mode="escape-json">
    <xsl:analyze-string select="." regex="{$regexp}">
        <xsl:matching-substring>
            <!-- This key() amounts to: $json-escapes/*[current() = @x]/@j 
                 but perhaps is a little faster. -->
            <xsl:value-of select="key('json-escapes', . ,$json-escapes)/@j"/>
        </xsl:matching-substring>
        <xsl:non-matching-substring>
            <xsl:value-of select="."/>
        </xsl:non-matching-substring>
    </xsl:analyze-string>
</xsl:template>

Regards,
David

Current Thread