如果代码点在给定范围内,则转换字符

时间:2012-05-29 12:16:35

标签: xslt xslt-2.0

我有几个包含unicode字符的XML文件,其代码点值介于57600和58607之间。目前这些文件在我的内容中显示为方块,我想将它们转换为元素。

所以我想要实现的是:

<!-- current input -->
<p> Follow the on-screen instructions.</p>  
<!-- desired output-->
<p><unichar value="58208"/> Follow the on-screen instructions.</p>
<!-- Where 58208 is the actual codepoint of the unicode character in question -->

我已经使用tokenizer愚弄了一下,但是因为你需要引用split,所以结果很复杂。

有关如何解决这个问题的建议吗?我一直在尝试下面的一些东西,但是被击中了(不介意语法,我知道它没有任何意义)

<xsl:template match="text()">
 -> for every character in my string
    -> if string-to-codepoints(current character) greater then 57600 return <unichar value="codepoint value"/>
       else return character
</xsl:template>

2 个答案:

答案 0 :(得分:3)

此转化

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes"/>

 <xsl:template match="/*">
     <p>
      <xsl:for-each select="string-to-codepoints(.)">
        <xsl:choose>
            <xsl:when test=". > 57600">
              <unichar value="{.}"/>
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select="codepoints-to-string(.)"/>
            </xsl:otherwise>
        </xsl:choose>
      </xsl:for-each>
     </p>
 </xsl:template>
</xsl:stylesheet>

应用于提供的XML文档

<p> Follow the on-screen instructions.</p>

生成想要的正确结果

<p><unichar value="58498"/> Follow the on-screen instructions.</p>

解释:正确使用标准XPath 2.0函数 string-to-codepoints() codepoints-to-string()

答案 1 :(得分:3)

这听起来像是analyze-string的工作,例如

<xsl:template match="text()">
  <xsl:analyze-string select="." regex="[&#57600;-&#58607;]">
    <xsl:matching-substring>
       <unichar value="{string-to-codepoints(.)}"/>
    </xsl:matching-substring>
    <xsl:non-matching-substring>
      <xsl:value-of select="."/>
    </xsl:non-matching-substring>
  </xsl:analyze-string>
</xsl:template>

未测试。

相关问题