How can I translate ' into an apostrophe in xslt

廉价感情. 提交于 2019-12-25 06:33:19

问题


The relevant parts of the code:

<xsl:variable name="apos">'</xsl:variable>
<xsl:variable name="and" select='"&#039;"' />

<xsl:value-of select="translate(products_name/node(),$and,$apos)"/>

I'm thinking this should be a simple thing and that the above code should work but it doesn't effect the output at all.

(I used variables because names cannot begin within an ampersand and using just an apostrophe brings up a compile error.)

I've tested the code to make sure the translate is working using strings and there are no errors there.

Any help would be greatly appreciated.


回答1:


You are on the right track, but not yet there: Your problem is, that XSL is a language that itself is written using XML. For all XML languages, the parser automatically decodes XML entities. The XSLT engine only comes afterwards.

As a result, the XSLT engine neither does nor can distinguish whether you wrote ' or &#039; - it's the same. For your problem, this has two effects:

  1. You have to use a variable containing the apostrope - this is because the apostrophe itself is reserved for string literals in expressions that may contain functions. Even for <xsl:value-of select="translate(products_name/node(),$and,'&#039;')"/>, the XML parser transforms the entity into an apostrophe, i.e. <xsl:value-of select="translate(products_name/node(),$and,''')"/>

  2. You have to escape the ampersand used in the string you search for: for the XSL engine, the variable "and" contains the value ', i.e. you are replacing an apostrophe with an apostrophe.

Working solution:

<xsl:variable name="apos">'</xsl:variable>
<xsl:value-of select='translate(text(), "&amp;#039;", $apos)'/>



回答2:


Technically, there's no difference in any XML between &apos;, &#39; and &#x27;, they're different ways of representing exactly the same thing. Therefore, that translate call shouldn't do anything.

It depends on how you're transforming it, where that output is (attribute value or element?), and how the output is serialized to text, but your problem isn't with your XSLT.



来源:https://stackoverflow.com/questions/6651000/how-can-i-translate-039-into-an-apostrophe-in-xslt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!