【问题标题】:Transforming numbers to Roman numbers by transforming an XML file via XSLT通过 XSLT 转换 XML 文件将数字转换为罗马数字
【发布时间】:2018-01-02 20:16:44
【问题描述】:

我有以下 xml 输入:

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

我想输出以下内容:

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

通过编写 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>

【问题讨论】:

    标签: xml xslt transform xslt-2.0


    【解决方案1】:

    试试:

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

    数字应介于 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>
    

    请注意,撒克逊人至少支持最大为 9999 的罗马数字: http://xsltransform.net/bEzjRKe

    【讨论】:

    • 您可能希望在输出中包含&lt;xsl:copy&gt;..,但为什么要坚持使用 XSLT 1 或 2?此解决方案适用于任何一个。
    • @Flynn1179 感谢您的关注。-- 至于版本,我问过,以便知道在哪里寻找答案。碰巧,答案也适用于 XSLT 1.0,但情况并非总是如此。
    • 如何添加一些验证?当输入数字 0 时应该是一个错误,而且 XSLT 可以处理最多 3xxx 的数字。因此,罗马数字中要求的最高字母将是“M”。因此,例如,任何高于 3999 的数字都应该无效。所以简而言之,数字应该在 1 到 3999 之间。
    • 输入未通过此验证时的预期结果是什么?
    • @michael.hor257k 有一个文本输出消息“请输入一个介于 1 和 3999 之间的数字”
    猜你喜欢
    • 2012-10-27
    • 2019-01-09
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    相关资源
    最近更新 更多