MathML parsing for simple math expression

I use the MathDox formula editor to create MathML. Now I want to convert the MathML created by MathDox into an expression that I can evaluate later to find the answer.

For eg:

MathML:
<math xmlns='http://www.w3.org/1998/Math/MathML'>
 <mrow>
  <mn>3</mn>
  <mo>+</mo>
  <mn>5</mn>
 </mrow>
</math>

Want to convert to expression as:
3+5

Now I can use 3 + 5 to get an answer of 8.

I was looking for a javascript or C # solution for this conversion. I tried to do this, but did not get much help. I found a slightly more suitable solution here , but this is a desktop application and commercial. However, I want an open source web application solution for my problem. Any help would be appreciated.

.. , , .

+1
1

, JavaScript:

  • MathML XML DOM
  • XML DOM
  • "eval",

:

function getDOM(xmlstring) {
    parser=new DOMParser();
    return parser.parseFromString(xmlstring, "text/xml");
}

function remove_tags(node) {
    var result = "";
    var nodes = node.childNodes;
    var tagName = node.tagName;
    if (!nodes.length) {
        if (node.nodeValue == "π") result = "pi";
        else if (node.nodeValue == " ") result = "";
        else result = node.nodeValue;
    } else if (tagName == "mfrac") {
        result = "("+remove_tags(nodes[0])+")/("+remove_tags(nodes[1])+")";
    } else if (tagName == "msup") {
        result = "Math.pow(("+remove_tags(nodes[0])+"),("+remove_tags(nodes[1])+"))";
    } else for (var i = 0; i < nodes.length; ++i) {
        result += remove_tags(nodes[i]);
    }

    if (tagName == "mfenced") result = "("+result+")";
    if (tagName == "msqrt") result = "Math.sqrt("+result+")";

    return result;
}

function stringifyMathML(mml) {
   xmlDoc = getDOM(mml);
   return remove_tags(xmlDoc.documentElement);
}

// Some testing

s = stringifyMathML("<math><mn>3</mn><mo>+</mo><mn>5</mn></math>");
alert(s);
alert(eval(s));

s = stringifyMathML("<math><mfrac><mn>1</mn><mn>2</mn></mfrac><mo>+</mo><mn>1</mn></math>");
alert(s);
alert(eval(s));

s = stringifyMathML("<math><msup><mn>2</mn><mn>4</mn></msup></math>");
alert(s);
alert(eval(s));

s = stringifyMathML("<math><msqrt><mn>4</mn></msqrt></math>");
alert(s);
alert(eval(s));

, MathML. , .

mathml MathML ( ).

+3

All Articles