Converting from Roman Numerals to Numbers

Problem

You need to convert a Roman numeral to a number.

Solution

Roman numbers do not use a place value system; instead, the number is composed by adding or subtracting the fixed value of the specified Roman numeral characters. If the following character has a lower or equal value, you add; otherwise, you subtract:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:math="http://www.ora.com/XSLTCookbook/math"> <math:romans> <math:roman value="1">i</math:roman> <math:roman value="1">I</math:roman> <math:roman value="5">v</math:roman> <math:roman value="5">V</math:roman> <math:roman value="10">x</math:roman> <math:roman value="10">X</math:roman> <math:roman value="50">l</math:roman> <math:roman value="50">L</math:roman> <math:roman value="100">c</math:roman> <math:roman value="100">C</math:roman> <math:roman value="500">d</math:roman> <math:roman value="500">D</math:roman> <math:roman value="1000">m</math:roman> <math:roman value="1000">M</math:roman> </math:romans> <xsl:variable name="math:roman-nums" select="document('')/*/*/math:roman"/> <xsl:template name="math:roman-to-number"> <xsl:param name="roman"/> <xsl:variable name="valid-roman-chars"> <xsl:value-of select="document('')/*/math:romans"/> </xsl:variable> <xsl:choose> <xsl:when test="translate($roman,$valid-roman-chars,'')">NaN</xsl:when> <xsl:otherwise> <xsl:call-template name="math:roman-to-number-impl"> <xsl:with-param name="roman" select="$roman"/> ...

Get XSLT Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.