开发者

XSLT escaping characters for XML attributes

开发者 https://www.devze.com 2022-12-13 14:46 出处:网络
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 t

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开发者_如何学C 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>


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,


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

0

精彩评论

暂无评论...
验证码 换一张
取 消