[XSL-LIST Mailing List Archive Home] [By Thread] [By Date] [Recent Entries] [Reply To This Message]

Re: JSON-encoding strings in XSLT 2.0

Subject: Re: JSON-encoding strings in XSLT 2.0
From: David Cramer <david@xxxxxxxxxxxx>
Date: Tue, 10 Dec 2013 09:29:07 -0600
Re:  JSON-encoding strings in XSLT 2.0
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="/"/>

<!-- 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}">
            <!-- 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:value-of select="."/>


Current Thread


Purchasing Stylus Studio from our online shop is Easy, Secure and Value Priced!

Buy Stylus Studio Now

Download The World's Best XML IDE!

Accelerate XML development with our award-winning XML IDE - Download a free trial today!

Don't miss another message! Subscribe to this list today.
First Name
Last Name
Subscribe in XML format
RSS 2.0
Atom 0.3
Site Map | Privacy Policy | Terms of Use | Trademarks
Free Stylus Studio XML Training:
W3C Member
Stylus Studio® and DataDirect XQuery ™are products from DataDirect Technologies, is a registered trademark of Progress Software Corporation, in the U.S. and other countries. © 2004-2013 All Rights Reserved.