This is the mail archive of the xsl-list@mulberrytech.com mailing list .


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: translate function


Steve Fitzpatrick wrote:
> I'm using XSLT to tranform XML into HTML/JavaScript (using Xalan/Xerxes).  I
> am running into problems with quotes/apostrophes when I use XSL in
> combination with JavaScript.  If there is a quote or an apostrophe in the
> XML that I am taking the value-of, it causes problems with the quotes I am
> using to declare a string in JavaScript.  I have been unable to use the
> translate() function to solve this problem.  Does anyone have  any
> suggestions?  See the simplified example below:
> 
> XML:
> 
> <?xml version="1.0" encoding="UTF-8"?>
> <?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?>
> <root>
>     <myNode><![CDATA[It's me]]></myNode>
> </root>

CDATA sections are only for the XML parser and document author's benefit, in
theory, even though in DOM parsers they are treated differently than other
text. The application that processes this character data should not, in 
theory, ever be exposed to the fact that it was once in a CDATA section. 
It's just the character data content of an element. The only thing a CDATA 
section buys you is not having to escape the characters that would otherwise 
denote markup. ("<" and "&", really)

> XSL:
> 
> <?xml version="1.0" encoding="UTF-8"?>
> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
> version="1.0">
> <xsl:template match="/">
> <html>
> <head><title>Example</title></head>
> 
> <body>
>   <script language="JavaScript" type="text/javascript">
>       var myNode = '<xsl:value-of select="root/myNode"/>';
>       alert(myNode);
>   </script>
> </body>
> 
> </html>
> </xsl:template>
> </xsl:stylesheet>
> 
> 
> The resultant HTML page has a javascript error on it because of the
> apostrophe in <myNode>.  

You just need to do a simple search and replace. Well, "simple" is all 
relative, I guess. 

You want to replace each apostrophe with a backslash followed by an
apostrophe. (i.e., ' becomes \' ). The translate() XPath function only works
on single character translations, so it will do you no good. You need to go
through the string recursively. It's a little harder to understand than a
character-by-character walk-through like you would do in Java, but actually
fairly efficient.

The pattern is described and examples are given at 
http://www.dpawson.co.uk/xsl/replace.html

   - Mike
_____________________________________________________________________________
mike j. brown, software engineer at  |  xml/xslt: http://skew.org/xml/
webb.net in denver, colorado, USA    |  personal: http://hyperreal.org/~mike/

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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]