views:

824

answers:

4

Using XSLT and XPath 1.0, I have a string I want to escape for use on a URL, for example:

<description>one word &amp; another</description>

So, the text() of the description element should get URL escaped.

How would I do this?

Using C# (XslCompiledTransform) the code would be:

string a = Server.UrlEncode("one word & another");

And would produce:

one+word+%26+another

Any suggestions?

Thanks,

Matt.

+1  A: 

In XML (and therefore XSL) you need to escape the &, > and < using

&amp;
&lt;
&gt;
rsp
+1, although you generally do not *need* to escape `>`. http://www.w3.org/TR/2008/REC-xml-20081126/#syntax
Tim
True as this might be, this is watering down people's perception. It's simpler (and better, probably) to remember that `>` is not an exception to the rule.
Tomalak
+1  A: 

The fragment <description>one word & another</description> resembles XML, but the naked ampersand is illegal. XSL requires legal XML.

One way to make it legal without substituting &amp; is to make the text into a CDATA section:

<description><![CDATA[one word & another]]></description>
Ewan Todd
Absolutely correct. I have adjusted my code snippet to compensate. Do you have an answer to my question, which is actually about how to replace the URL-illegal characters with valid ones ie to URL-escape the text?
Matt W
This is correct, but it's not an answer to the question.
elzapp
+2  A: 

There's nothing built in to do this, but rather than reinvent the wheel there are style sheets already out there e.g.:

http://skew.org/xml/stylesheets/url-encode/

The transforms are straightforward but (hopefully) someone else will have done the debugging for you...

FinnNk
So there's really no way to convert any short piece of text into a link, easily?
Matt W
Not using XSLT alone - it's a generic transformation language, so it's not suprising really. You could start mixing in other technologies to simplify the task, for example you could manipulate the source XML (codeproject.com/KB/cpp/myXPath.aspx) by using Server.UrlEncode after picking out the nodes from an XmlDocument with xpath and then push the result through XSLT. Depends on the context really.
FinnNk
Thank you, those style sheets have helped enormously.
Matt W
+1  A: 

Is it possible for you to use XSLT 2.0? I only mention it because there is a nifty URL encoding function which would sort out all your problems..

<xsl:value-of select="url:encode('This is URL encoded')" />
James
I would like to use XSLT 2, but I'm not sure which implementation to use for .NET
Matt W
Maybe this will point you in the right direction: http://stackoverflow.com/questions/94047/are-net-3-5-xpath-classes-and-methods-xslt-2-0-compatible
James