tags:

views:

427

answers:

2

I am working in a framework (cocoon) which means that the pages after I produce them are re-transformed by processes I have little or no control of. What I am doing is making a web service call, then transforming the results into an HTML page for presentation. Sounds like a job for XSLT. Everything works fine, until the data returned in an XML text node has an '&' character in it. The returned XML is properly escaped, but I want to put it into the href attribute of an anchor node. Everything I have tried ends up with the unescaped '&' character showing up in the href attribute. For example:

If the node returned from the web service looks like:

<ns:name>Foo&amp;Bar</ns:name>

The resulting <a> token (in the page source) looks like:

<a href="ADifferentPage.jsp?name=Foo&Bar">Foo&amp;Bar</a>

My current XSLT code looks like:

<a>
  <xsl:attribute name="href">
    ADifferentPage.jsp?name=<xsl:value-of select="ns:name" />
  </xsl:attribute>
  <xsl:value-of select="ns:name" />
</a>

The desired result is:

<a href="ADifferentPage.jsp?name=Foo&amp;Bar">Foo&amp;Bar</a>
A: 

The result is as expected. When the output method is set to "html", attribute values are not xml escaped. If it's possible, try switching the output method to "xml", when you're trying to deliver xml/xhtml

Sander Rijken
A: 

Ok. While Sander's answer worked for what I thought I wanted, it didn't actually solve my problem. I should have looked at the "Encode versus Escape" question elsewhere. Since what I was trying to create was a valid href, the contents of the variable actually needed to be encoded.

Here is the code that actually passed a valid href:

<a>
  <xsl:attribute name="href">
    ADifferentPage.jsp?name=<xsl:value-of select="ns:name" mode="encode"/>
  </xsl:attribute>
  <xsl:value-of select="ns:name" />
</a>

<xsl:template match="ns:name" mode="encode">
   <xsl:value-of select="url:encode(text())" />
</xsl:template>

You also need some code (that was provided to me by my company so I can't share it) to do the encoding in Java as an extension,

dmccorison