[Top] [All Lists]

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

2021-07-15 10:28:46

I have XML documents like this:

   <equation>(Fahrenheit - 32) * (5/9)</equation>

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 

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
XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list
EasyUnsubscribe: http://lists.mulberrytech.com/unsub/xsl-list/1167547
or by email: xsl-list-unsub(_at_)lists(_dot_)mulberrytech(_dot_)com

<Prev in Thread] Current Thread [Next in Thread>