Subject: [xsl] select="substring-before($str,"'")" !!! From: phil_endecott@xxxxxxxxxxx Date: Tue, 16 Jan 2001 07:50 -0500 |
Dear XSL experts, This question is about quoting and escaping string literals. I have an XSLT stylesheet that transforms an XML document to HTML. The HTML contains some javascript. The XML document contains people's names that come out in writeln() statements in the javascript. For example: <name>Fred Bloggs</name> gets transformed to document.writeln('Fred Bloggs'); with the crucial bit of XSLT being something like document.writeln('<xsl:value-of select="name"/>'); This all worked fine until someone came along called Sandra O'Boyle. My naive implementation translates this to document.writeln('Sandra O'Boyle'); which isn't valid javascript, because of the mismatched quotes. What it needs to say is document.writeln('Sandra O\'Boyle'); I noticed that XSLT (or more correctly XPath) has a translate function but this doesn't seem to do quite what I want. translate() will only replace one character with one character. So I have to do it the hard way: <xsl:template name="escape-string-for-javascript"> <xsl:param name="str"/> <xsl:choose> <xsl:when test="contains($str,"'")"> <xsl:variable name="before-first-apostrophe"><xsl:value-of select="substring-before($str,"'")"/></xsl:variable> <xsl:variable name="after-first-apostrophe"><xsl:value-of select="substring-after($str,"'")"/></xsl:variable> <xsl:value-of select="$before-first-apostrophe"/>\'<xsl:call-template name="escape-string-for-javascript"><xsl:with-param name="str"><xsl:value-of select="$after-first-apostrophe"></xsl:with-param></xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$str"> </xsl:otherwise> </xsl:choose> </xsl:template> and call it like this: document.writeln('<xsl:call-template name="escape-string-for-javascript"><xsl:with-param name="str"><xsl:value-of select="name"/></xsl:with-param></xsl:call-template>'); OK, all fine except for one problem. In a couple of places I have the string "'". XPath allows two forms for string literals: "...." and '....'. If I delimit the string with ""s I'm allowed 's inside. If I delimit it with "s I'm allowed "s inside. So I'm using ""s to enclose the ' that I want to match. But ""s are also used to delimit the value for the select attribute that encloses all of this. This has reached the limit of my understanding of XSL. Is there some magic I can do with "? Some alternative XML syntax to allow quotes inside attribute values? Any help much appreciated. Regards, --Phil. XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list
Current Thread |
---|
|
<- Previous | Index | Next -> |
---|---|---|
RE: [xsl] Parameter from asp, Michael Kay | Thread | Re: [xsl] select="substring-before(, David Carlisle |
Re: [xsl] Indexing a fop generated , David Carlisle | Date | [xsl] for-each -- strange multiplic, mario . jeckle |
Month |