Re: [xsl] How to dynamically evaluate an equation in the input XML document?

Subject: Re: [xsl] How to dynamically evaluate an equation in the input XML document?
From: "Michael Kay mike@xxxxxxxxxxxx" <xsl-list-service@xxxxxxxxxxxxxxxxxxxxxx>
Date: Thu, 15 Jul 2021 15:28:39 -0000
> I have XML documents like this:
> <Convert-to-Celsius>
>    <equation>(Fahrenheit - 32) * (5/9)</equation>
>    <variable>
>        <name>Fahrenheit</name>
>        <value>32</value>
>    </variable>
> </Convert-to-Celsius>
> The document contains an equation which might contain variables. If it does
contain variables, then I need to fetch their values and replace the variables
in the equation with their values and then compute the value of the equation.

As Dimitre points out, this is an expression (or formula), not an equation.

Writing a simple expression interpreter is a common exercise on undergraduate
computer science courses, and it's not clear from your question whether you
are familiar with the basic principles. The typical solution would be to write
a lexical analyser that splits the expression into tokens, then add a syntax
analyser to build a syntax tree that represents the grammatical structure of
the expression, and then (using the interpreter design pattern) write a
depth-first recursive tree walker that evaluates the expression nodes in this
tree; the interpreter would have access to a context object that contains the
bindings of variables to values, typically as an XDM map.

If this description is too terse, then there are plenty of textbooks that
explain it in more detail.

You can short-circuit the process by generating the lexical analyser and
syntax analyser directly from a BNF specification using a parser generator; a
popular choice in this community is Rex from Gunther Rademacher (though this
does an excellent job, it suffers from (a) not being published as open source,
and (b) being poorly documented). A benefit of Rex is that you can generate
the parser components as XSLT or XQuery code.

Many people in this community would choose to use XPath as the expression
language rather than inventing your own. That has the benefit that you don't
need to specify and implement the language yourself, it's already been done;
and you can then use xsl:evaluate directly for the evaluation.

Michael Kay

Current Thread