[XSL-LIST Mailing List Archive Home] [By Thread] [By Date] [Recent Entries] [Reply To This Message] Re: How to dynamically evaluate an equation in the inp
> 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 Saxonica
|
PURCHASE STYLUS STUDIO ONLINE TODAY!Purchasing Stylus Studio from our online shop is Easy, Secure and Value Priced! Download The World's Best XML IDE!Accelerate XML development with our award-winning XML IDE - Download a free trial today! Subscribe in XML format
|