XSLT删除非ASCII

Ren*_*ene 5 xml xslt xpath

我需要使用XSLT修改XML文档.我想用空格替换所有非ASCII字符.

输入示例:

<input>azerty12€_étè</input>
Run Code Online (Sandbox Code Playgroud)

只允许这些字符:

!"#$%&'()*+,-./0123456789:;=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
Run Code Online (Sandbox Code Playgroud)

预期产量:

 <input>azerty12 _ t </input>
Run Code Online (Sandbox Code Playgroud)

mic*_*57k 5

假设您仅限于XSLT 1.0,您可以尝试:

<xsl:variable name="ascii">!"#$%&amp;'()*+,-./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>
Run Code Online (Sandbox Code Playgroud)

这有点像黑客攻击:只要$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"> !"#$%&amp;'()*+,-./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>
Run Code Online (Sandbox Code Playgroud)


kjh*_*hes 5

XSLT 2.0解决方案

这个输入XML

<input>azerty12€_étè</input>
Run Code Online (Sandbox Code Playgroud)

给了这个XSLT

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
  <xsl:output method="xml" omit-xml-declaration="yes"/>

  <xsl:template match="input">
    <xsl:copy>
      <xsl:value-of select="replace(., '\P{IsBasicLatin}', ' ')"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

将生成此输出XML

<input>azerty12 _ t </input>
Run Code Online (Sandbox Code Playgroud)

按照要求.