正在将MathML解析为纯数学表达式

本文关键字:表达式 MathML | 更新日期: 2023-09-27 18:26:35

我正在使用MathDox公式编辑器来生成MathML。现在,我想将MathDox生成的MathML转换为表达式,稍后可以使用该表达式进行求值以找到答案。

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

现在我可以用3+5得到答案8。

我正在搜索用于此转换的javascriptc#解决方案。试着用谷歌搜索,但没有得到太多帮助。我在这里找到了一个更接近的解决方案,但它也是一个桌面应用程序和商业应用程序。然而,我想要解决我的问题的开源web应用程序解决方案。任何帮助都将不胜感激。

注意:为了简单起见,我在上面的例子中只提到了简单的加法,但mathml也可以包含类似于复杂表达式的派生和log。

正在将MathML解析为纯数学表达式

这可以在JavaScript中使用以下步骤来实现:

  1. 从MathML转换为XML DOM
  2. 从XML DOM转换为纯文本
  3. 使用"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(用于代码的测试部分)。