对我来说,这只适用于 Firefox。这项工作的主要工具是createElementNS 和getElementsByTagNameNS。此外,我不确定您从哪里获得您的 openmath 文档,但我将通过 AJAX 检索它。
所以,假设你的文件结构是:
/root
+-/js
| +-convert.js
|
+-/xml
| +-openmath.xml
|
+-index.html
你的文件如下:
index.html
关于index.html 唯一需要注意的是,我们在<math> 元素上设置了一个id,我们希望将转换后的标签放在该元素下。我们还包括 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 标签,我们就将它们作为子标签添加到index.html 中存在的<math> 标签下。
(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();
});
}());