我正在使用 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。
我正在为这种转换寻找javascript 或c# 解决方案。试图谷歌它,但没有得到太多帮助。我找到了更接近的解决方案 here ,但它也是一个桌面应用程序和商业应用程序。但是,我想要解决我的问题的开源 Web 应用程序解决方案。任何帮助将不胜感激。
注意:为简单起见,我在上面的示例中只提到了简单的加法,但 mathml 也可以包含复杂的表达式,如推导和对数。
最佳答案
这可以在 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。例如,添加三 Angular 函数或任何其他自定义函数会很容易。
出于这篇文章的目的,我使用了 mathml editor 中的工具构建 MathML(用于代码的测试部分)。
关于javascript - 将 MathML 解析为纯数学表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26357109/