concat, quotation mark and apostrophe combination problems

强颜欢笑 提交于 2019-12-01 18:48:46

In XML/XSLT you do not escape characters with a backslash.

  • In XML you can use entity references.
  • In XSLT you can use entity references and variables.

The problem with the apostrophe inside of your concat strings is that the XML parser loading the XSLT will expand it before the concat gets evaluated by the XSLT engine; so you can't use an entity reference for the apostrophe character unless it is wrapped in double quotes (or entity references for double quotes, as Dimitre Novatchev's answer demonstrates).

  • Use the entity reference " for the double quote ".
  • Create a variable for the apostrophe character and reference the variable as one of the components of the concat()

Applied in the context of an XSLT:

<xsl:variable name="apostrophe">'</xsl:variable>

<xsl:value-of select="concat( 
            'this is; &quot;a sample',
            //XML_NODE,
            '&quot;; &quot;using an apostrophe ',
            $apostrophe,
            ' in text&quot;'
            )" />

If you need a 100% XPath solution that avoids the use of XSLT variables, then Dimitre's answer would be best.

If you are concerned with how easy it is to read, understand, and maintain, then Michael Kay's suggestion to use XSLT variables for the quote and apostrophe might be best.

No variable is necessary:

Here is an example how to produce the wanted output in two ways:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:template match="/">
  <xsl:text>this is "a sample XML_NODE_VALUE"; "using an apostrophe ' in text"</xsl:text>
  =============
  <xsl:value-of select=
   "concat('this is ',
           '&quot;a sample XML_NODE_VALUE&quot;; &quot;',
           &quot;using an apostrophe &apos; in text&quot;,
           '&quot;'
          )
   "/>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on any XML document (not used), the wanted output is produced:

this is "a sample XML_NODE_VALUE"; "using an apostrophe ' in text"
=============
this is "a sample XML_NODE_VALUE"; "using an apostrophe ' in text"

I find the easiest solution is to declare variables:

<xsl:variable name="apos">'</xsl:variable>
<xsl:variable name="quot">"</xsl:variable>
<xsl:value-of select="concat('This is ', $quot, "a sample using ", $apos)"/>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!