通过 XSLT 转换 XML 文件将数字转换为罗马数字

hab*_*bed 2 xml xslt transform xslt-2.0

我有以下 xml 输入:

<root>
    <calc>
        <arab>42</arab>
    </calc>
    <calc>
        <arab>137</arab>
    </calc>
</root>
Run Code Online (Sandbox Code Playgroud)

我想输出以下内容:

<root>
    <calc>
        <roman>XLII</roman>
        <arab>42</arab>
    </calc>
    <calc>
        <roman>CXXXVII</roman>
        <arab>137</arab>
    </calc>
</root>
Run Code Online (Sandbox Code Playgroud)

通过编写 XSLT。到目前为止,我已经编写了这个 XSLT,但是还需要做什么才能输出正确的输出呢?

<?xml version="1.0" encoding="UTF-8"?>
    <xsl:transform
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
      xmlns:num="http://whatever"
      version="2.0" exclude-result-prefixes="xs num">

      <xsl:output method="xml" version="1.0"
        encoding="UTF-8" indent="yes"/>


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

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

mic*_*57k 5

尝试:

<xsl:template match="calc">
    <xsl:copy>
        <roman>
            <xsl:number value="arab" format="I"/>
        </roman>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

数字应介于 1 到 3999 之间。

要验证数字是否在 1 到 3999 的范围内,您可以执行以下操作:

<xsl:template match="calc">
    <xsl:copy>
        <xsl:choose>
            <xsl:when test="1 le number(arab) and number(arab) le 3999">
                <roman>
                    <xsl:number value="arab" format="I"/>
                </roman>
            </xsl:when>
            <xsl:otherwise>
                <xsl:message terminate="no">Please enter a number between 1 and 3999</xsl:message>
            </xsl:otherwise>
        </xsl:choose>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

请注意,Saxon 至少支持高达 9999 的罗马数字: http://xsltransform.net/bEzjRKe