Transforming numbers to Roman numbers by transform

2019-04-12 19:56发布

I have the following xml input:

<root>
    <calc>
        <arab>42</arab>
    </calc>
    <calc>
        <arab>137</arab>
    </calc>
</root>

I want to output the following:

<root>
    <calc>
        <roman>XLII</roman>
        <arab>42</arab>
    </calc>
    <calc>
        <roman>CXXXVII</roman>
        <arab>137</arab>
    </calc>
</root>

By writing a XSLT. So far I wrote this XSLT but what else needs to be done to output the right output?

<?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>

1条回答
Fickle 薄情
2楼-- · 2019-04-12 20:13

Try:

<xsl:template match="calc">
    <xsl:copy>
        <roman>
            <xsl:number value="arab" format="I"/>
        </roman>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

numbers should be between 1 and 3999.

To validate that the numbers are in the range of 1 to 3999, you could do:

<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>

Note that Saxon at least supports roman numerals up to 9999: http://xsltransform.net/bEzjRKe

查看更多
登录 后发表回答