如何编写XSLT模板输出特殊字符反斜杠及完善指定模板
我来帮你搞定这两个XSLT模板的问题——输出反斜杠,还有完善那个不完整的removequotes模板:
1. 输出反斜杠(\)的XSLT模板
在XSLT里,反斜杠不属于XML的特殊转义字符,直接输出很简单。如果需要专门做一个模板来输出反斜杠,可以用下面的代码:
<xsl:template name="output-backslash"> <!-- 用xsl:text确保输出纯文本,避免多余空格 --> <xsl:text>\</xsl:text> </xsl:template>
如果只是在其他模板里需要插入反斜杠,直接写<xsl:text>\</xsl:text>就行,比如拼接字符串时:
<xsl:value-of select="concat('文件路径:', '\', 'docs\report.pdf')"/>
2. 完善removequotes模板
你提供的模板片段是用来移除文本中的引号,还涉及处理带反斜杠转义的引号(\"),我把截断的部分补全,同时修正逻辑,确保转义的反斜杠能保留,普通引号直接移除:
<xsl:template match="node/@TEXT | text()" name="removequotes"> <xsl:param name="pText" select="normalize-space(.)"/> <xsl:choose> <!-- 文本中没有引号时直接输出 --> <xsl:when test="not(contains($pText, '&quot;'))"> <xsl:copy-of select="$pText"/> </xsl:when> <xsl:otherwise> <!-- 优先处理带反斜杠转义的引号:保留反斜杠,去掉引号 --> <xsl:choose> <xsl:when test="contains($pText, '&#92;&quot;')"> <xsl:value-of select="concat(substring-before($pText, '&#92;&quot;'), '\')"/> <xsl:call-template name="removequotes"> <xsl:with-param name="pText" select="substring-after($pText, '&#92;&quot;')"/> </xsl:call-template> </xsl:when> <!-- 处理普通引号,直接移除 --> <xsl:otherwise> <xsl:value-of select="substring-before($pText, '&quot;')"/> <xsl:call-template name="removequotes"> <xsl:with-param name="pText" select="substring-after($pText, '&quot;')"/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:otherwise> </xsl:choose> </xsl:template>
这个模板的逻辑是:
- 递归处理文本内容,默认对输入文本做规范化空格处理
- 如果文本里没有引号,直接输出内容
- 如果有引号,先检查是不是转义的
\":是的话保留反斜杠、去掉引号,再递归处理剩下的文本;如果是普通引号,直接移除后递归处理剩余内容
内容的提问来源于stack exchange,提问作者Adithya Sajjanam
相关产品推荐
相关产品推荐

