Search code examples
xmlxpathxqueryxproc

evaluate xml value as equation


I'm trying to evaluate a equation inserted as value of xml tag using Xquery, Xpath or Xproc - in simple word in pure XML. I'm beginner here, but in my opinion it should be doable. To better demonstrate what I want to achieve, please see this example:

<inp> 
 <data>
   <a>5</a>
   <b>4</b>
 </data>
 <eq>
   a+b
 </eq>
</inp>

Now there will be some magic... and as result I'd like to get something like:

 <res>
  9
 </res>

Could you help me with the magic involved? At least point to correct tech - xquery, xpath or xproc to do it. Thanks. Todor

EDIT: To avoid accusations that I didn't do any research - it's part of the question. I'm trying to determine the best technology from xml family to use. That's why I'm asking for direction to solution not for solutions :). Thanks. PS> of course, I'd be grateful for solutions, but I don't want to use more of your time than necessary .


Solution

  • If you can change the syntax to be XPath-compatible, so it's $a+$b rather than a+b, then it's easy to do using XSLT 3.0's xsl:evaluate or the eval() extensions offered in a processor-specific way by various XSLT 1.0 and 2.0 processors. The 3.0 solution would look like this:

    <xsl:template match="inp"
      <xsl:evaluate xpath="eq" 
           with-params="map:merge(
                for $p in data/* return map{node-name($p): data($p)})"/>
    </xsl:template>
    

    I would add that I implemented an application for a client that did this many years ago, and I've seen similar things many times. In their case they were using an XML document containing formulae which determined the level of approval needed for different classes of capital spending.