xslt-1.0 - XSLT 1.0 模板的多次调用
问题描述
我需要替换 XML 文件中的字符串。我正在尝试使用 XSLT 来做到这一点。我想对需要替换的每个字符串使用调用模板。
当我多次调用模板时,只有最后一次调用正常。
我需要更改的 XML 文件:我想替换字符串
‘
和
—
按空格
<?xml version="1.0" encoding="UTF-8"?>
<RAPPORT>
<reason>start test_145 : ‘ and test_ 151 : — _end_test</reason>
</RAPPORT>
我使用的模板:
<xsl:template name="globalReplace">
<xsl:param name="outputString"/>
<xsl:param name="target"/>
<xsl:param name="replacement"/>
<xsl:choose>
<xsl:when test="contains($outputString,$target)">
<xsl:value-of select="concat(substring-before($outputString,$target),$replacement)"/>
<xsl:call-template name="globalReplace">
<xsl:with-param name="outputString" select="substring-after($outputString,$target)"/>
<xsl:with-param name="target" select="$target"/>
<xsl:with-param name="replacement" select="$replacement"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$outputString"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
多次调用:
<xsl:template match="text()">
<xsl:call-template name="globalReplace">
<xsl:with-param name="outputString" select="."/>
<xsl:with-param name="target" select="'‘'"/>
<xsl:with-param name="replacement" select="' '"/>
</xsl:call-template>
</xsl:template>
<xsl:template match="text()">
<xsl:call-template name="globalReplace">
<xsl:with-param name="outputString" select="."/>
<xsl:with-param name="target" select="'—'"/>
<xsl:with-param name="replacement" select="' '"/>
</xsl:call-template>
</xsl:template>
预期结果 :
<?xml version="1.0" encoding="UTF-8"?>
<RAPPORT>
<reason>debut test_test_145 et test 151 _fin test</reason>
</RAPPORT>
我实际上得到了什么:
<?xml version="1.0" encoding="UTF-8"?>
<RAPPORT>
<reason>debut test_test_145**PUI** et test 151 _fin test</reason>
</RAPPORT>
PUI意味着一个意想不到的字符而不是所需的空间
解决方案
您有两个匹配 text()
的模板。仅应用最后一个 - 请参阅:https ://www.w3.org/TR/1999/REC-xslt-19991116#conflict
在给定的示例中,您可以简单地使用该translate()
函数一次完成所有工作,因为您要替换的“字符串”实际上是字符:
XML
<?xml version="1.0" encoding="UTF-8"?>
<RAPPORT>
<reason>start test_145 : ‘ and test_ 151 : — _end_test</reason>
</RAPPORT>
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="translate(., '‘—', ' ')"/>
</xsl:template>
</xsl:stylesheet>
结果
<?xml version="1.0" encoding="UTF-8"?>
<RAPPORT>
<reason>start test_145 : and test_ 151 : _end_test</reason>
</RAPPORT>
推荐阅读
- python - 函数在 exec 中看不到带有提供的局部变量的局部变量
- variables - 带有尾随 P 的布尔变量的命名约定
- javascript - 列出所有“真实”变量
- excel - 如何嵌套多个 if 函数以在 Excel 中产生不同的 vlookup?
- vba - VBA Adobe Acrobat Sub 之前成功后失败
- javascript - KnockoutJS Grid 添加项目
- reactjs - 材质 UI MenuItem 未显示具有硬编码值的选定项目
- javascript - 将 Javascript 移动到模块后出现“无法读取未定义的属性 ClassList”错误
- sql - 出现服务器错误 - 这是什么意思?
- css - CSS3背景过滤器不适用于固定菜单