我需要使用 XSLT 修改 XML 文档。我想用空格替换所有非 ASCII 字符。
示例输入:
<input>azerty12€_étè</input>
只允许使用这些字符:
!"#$%&'()*+,-./0123456789:;=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
预期输出:
<input>azerty12 _ t </input>
最佳答案
假设您仅限于 XSLT 1.0,您可以尝试:
<xsl:variable name="ascii">!"#$%&'()*+,-./0123456789:;=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~</xsl:variable>
<xsl:variable name="spaces" select="' '" />
<xsl:template match="input">
<xsl:copy>
<xsl:value-of select="translate(., translate(., $ascii, ''), $spaces)"/>
</xsl:copy>
</xsl:template>
这有点 hack:只要 $spaces
变量中有足够的空间来容纳输入中的所有非 ASCII 字符,它就会一直有效。
如果你不想依赖这样的假设,你将不得不使用递归模板来一个接一个地替换它们:
<xsl:template match="input">
<xsl:copy>
<xsl:call-template name="replace-non-ascii">
<xsl:with-param name="text" select="."/>
</xsl:call-template>
</xsl:copy>
</xsl:template>
<xsl:template name="replace-non-ascii">
<xsl:param name="text"/>
<xsl:variable name="ascii"> !"#$%&'()*+,-./0123456789:;=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~</xsl:variable>
<xsl:variable name="non-ascii" select="translate($text, $ascii, '')" />
<xsl:choose>
<xsl:when test="$non-ascii">
<xsl:variable name="char" select="substring($non-ascii, 1, 1)" />
<!-- recursive call -->
<xsl:call-template name="replace-non-ascii">
<xsl:with-param name="text" select="translate($text, $char, ' ')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
关于xml - XSLT 删除非 ASCII,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34932344/