使用XSLT转换Unicode转义字符

时间:2014-10-21 15:41:28

标签: xml xslt saxon

有人可以说我如何将像\u00e4这样的Unicode代码点转义字符转换为XSLT中的真实字符ö吗?

我确实......

<text>Eine Repr\u00e4sentation des Objektes geh\u00f6rt...<text>

......我喜欢:

<text>Eine Repräsentation des Objektes gehört...<text>

1 个答案:

答案 0 :(得分:4)

这是多么有趣的事情......所以这是我提出的XSLT 2.0解决方案:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math" 
    exclude-result-prefixes="xs math f"
    xmlns:f="func" version="2.0">

    <xsl:template match="text">
        <xsl:copy>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="text/text()">
        <xsl:value-of select="f:unescapeCharachters(.)"/>
    </xsl:template>

    <xsl:function name="f:unescapeCharachters">
        <xsl:param name="text" as="xs:string"/>
        <xsl:analyze-string select="$text" regex="\\u([0-9|abcdefABCDEF]{{4}})">
            <xsl:matching-substring>
                <xsl:value-of select="codepoints-to-string(f:hex-to-dec(regex-group(1)))"/>
            </xsl:matching-substring>
            <xsl:non-matching-substring>
                <xsl:value-of select="."/>
            </xsl:non-matching-substring>
        </xsl:analyze-string>
    </xsl:function>

    <xsl:function name="f:hex-to-dec">
        <xsl:param name="hex"/>
        <xsl:variable name="hexvals" select="'0123456789ABCDEF'"/>
        <xsl:choose>
            <xsl:when test="$hex=''">0</xsl:when>
            <xsl:otherwise>
                <xsl:value-of
                    select="string-length(substring-before($hexvals,substring(upper-case($hex),1,1)))
                * math:pow(16,string-length($hex)-1) + f:hex-to-dec(substring($hex,2))"
                />
            </xsl:otherwise>
        </xsl:choose>
    </xsl:function>

</xsl:stylesheet>