我正在使用mathdox,在我的网页中插入方程式。我已经实现了我需要的所有符号和数学表达式,将它们作为openmath插入并将它们转换为MathML,但下标除外。我知道它应该像这样工作:
<OMOBJ xmlns='http://www.openmath.org/OpenMath' version='2.0' cdbase='http://www.openmath.org/cd'>
<OMA style='sub'>
<OMV name='x'/>
<OMI>2</OMI>
</OMA>
</OMOBJ>
应转换为
<math xmlns="http://www.w3.org/1998/Math/MathML">
<msub>
<mi>X</mi>
<mn>2</mn>
</msub>
</math>
但我找不到在javascript中实现它的方法或者在mathdox中找到它的现有实现。
答案 0 :(得分:1)
对我来说,这只适用于Firefox。这项工作的主要工具是createElementNS
和getElementsByTagNameNS
。此外,我不确定您从哪里获得openmath
文档,但我将通过AJAX
检索它。
因此,假设您的文件结构为:
/root
+-/js
| +-convert.js
|
+-/xml
| +-openmath.xml
|
+-index.html
您的文件如下:
<强>的index.html 强>
关于index.html
唯一需要注意的是我们在id
元素上设置<math>
,我们要将转换后的标记放在其下。我们还包含convert.js
JavaScript文件。
<html>
<head>
<title>Convert</title>
<script src="js/convert.js"></script>
</head>
<body>
<main>
<math xmlns="http://www.w3.org/1998/Math/MathML" id="target"></math>
</main>
</body>
</html>
<强> openmath.xml 强>
此文件只是您在问题中发布的XML,我们将转换为数学命名空间。
<OMOBJ xmlns='http://www.openmath.org/OpenMath' version='2.0' cdbase='http://www.openmath.org/cd'>
<OMA style='sub'>
<OMV name='x' />
<OMI>2</OMI>
</OMA>
</OMOBJ>
<强> convert.js 强>
convert.js
的工作方式是在xhr上加载openmath文档,然后使用DOMParser()
和parseFromString()
创建包含文档文本的新XML文档。然后,我们将该文档提供给mathSubscriptConverter()
,其中提取所有OMA
代码,从中获取相关数据,然后将其转换为msub
代码。获得msub
代码后,我们会将其添加为<math>
内index.html
标记下的子代。
(function () {
"use strict";
var mathNS = "http://www.w3.org/1998/Math/MathML",
openMathNS = "http://www.openmath.org/OpenMath",
xhr = new XMLHttpRequest();
function mathSubscriptConverter(openmathDoc) {
var target = document.getElementById("target"),
omas = openmathDoc.getElementsByTagNameNS(openMathNS, "OMA");
// Make sure we have a math element to put this under
if (target) {
// Iterate each OMA tag
Array.prototype.forEach.call(omas, function (oma) {
var omv, omi, msub, mi, mn;
// Get the first OMV
omv = oma.getElementsByTagNameNS(openMathNS, "OMV")[0];
// Get the first OMV
omi = oma.getElementsByTagNameNS(openMathNS, "OMI")[0];
// Create a subscript tag in the math namespace
msub = document.createElementNS(mathNS, "msub");
// Create an mi tag in the math namespace
mi = document.createElementNS(mathNS, "mi");
// Create an mn tag in the math namespace
mn = document.createElementNS(mathNS, "mn");
// Set our math attributes
mi.innerHTML = omv.getAttribute("name");
mn.innerHTML = omi.innerHTML;
// Add our new elements to the target
msub.appendChild(mi);
msub.appendChild(mn);
target.appendChild(msub);
});
}
}
// Wait for document load
document.addEventListener("DOMContentLoaded", function () {
// Load our openmath document
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var parser = new DOMParser(),
mdoc = parser.parseFromString(xhr.responseText, "application/xml");
mathSubscriptConverter(mdoc);
}
};
xhr.open("GET", "xml/openmath.xml", true);
xhr.send();
});
}());