动态替换匹配的特殊字符

时间:2019-02-16 02:43:17

标签: xslt-1.0 ibm-datapower

我有一个特殊字符文件(带有特殊字符列表)。我必须阅读该文件,并检查传入的请求是否具有任何特殊字符,如果是的话:将其替换为常量,否则:按原样移动

在xslt 1.0中尝试使用以下代码。

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" xmlns:regex="http://exlt.or/regular-expressions">
  <xsl:output method="xml" indent="yes"/>
  <xsl:variable name="charfile" select="document('chars.xml')"/>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>  

  <xsl:template match="text()">
    <xsl:call-template name="checkAndReplace">
      <xsl:with-param name="text" select="."/>
    </xsl:call-template>
  </xsl:template>

  <xsl:template name="checkAndReplace">
    <xsl:param name="text"/>
    <xsl:for-each select="$charfile/chars/char">
      <xsl:if test="contains($text,./value/text())">
        <xsl:copy-of select="translate($text,./value/text(),'*')"/>
      </xsl:if>      
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

chars.xml:

<?xml version="1.0" encoding="utf-8"?>
<chars>
  <char>
    <value>@#128;</value>
  </char>
  <char>
    <value>@#129;</value>
  </char>
  <char>
    <value>@#130;</value>
  </char>
</chars>

输入:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <child1>abc@#128;</child1>
  <child2>def@#129;</child2>
  <child3>hello</child3>
</root>

需要的输出:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <child1>abc*</child1>
  <child2>def*</child2>
  <child3>hello</child3>
</root>

1 个答案:

答案 0 :(得分:1)

假定列出特殊字符的文件实际上应如下所示:

chars.xml

<chars>
  <char>
    <value>&#128;</value>
  </char>
  <char>
    <value>&#129;</value>
  </char>
  <char>
    <value>&#130;</value>
  </char>
</chars>

您可以使用以下样式表:

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="*"/>

<xsl:param name="charfile" select="document('chars.xml')"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:variable name="search-chars">
    <xsl:for-each select="$charfile/chars/char">
        <xsl:value-of select="value"/>
    </xsl:for-each>
</xsl:variable>

<xsl:variable name="replace-chars">
    <xsl:for-each select="$charfile/chars/char">
        <xsl:text>*</xsl:text>
    </xsl:for-each>
</xsl:variable>

<xsl:template match="text()">
    <xsl:value-of select="translate(., $search-chars, $replace-chars)"/>
</xsl:template>

</xsl:stylesheet>

输入以下内容:

XML

<root>
  <child1>abc&#128;</child1>
  <child2>def&#129;</child2>
  <child3>hello</child3>
</root>

输出将是:

结果

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <child1>abc*</child1>
  <child2>def*</child2>
  <child3>hello</child3>
</root>
相关问题