最近学了一下在 html 页面中读取并处理 XML 数据的方法。
以下是我们的 XML 例子,文件名为info.xml
:
<?xml version="1.0" encoding="utf-8"?>
<root>
<row>
<Name>John</Name>
<Age>30</Age>
</row>
<row>
<Name>Jane</Name>
<Age>32</Age>
</row>
</root>
通过 d3.xml("info.xml")
来读取 XML 文件。注意不同版本的 API 不太一样。
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
async function loadXML(filename) {
const root = await d3.xml(filename);
var names = root.getElementsByTagName("Name");
var ages = root.getElementsByTagName("Age");
var len = names.length;
var data = "";
for (var i = 0; i < len; i++) {
data += "姓名:";
data += names[i].firstChild.nodeValue;
data += " 年龄:";
data += ages[i].firstChild.nodeValue;
data += " ";
}
console.log(data)
}
loadXML("info.xml");
</script>
这是一种现代浏览器支持的方法。
<script>
function loadXML(filename) {
var xhr = new XMLHttpRequest();
xhr.open("GET", filename, true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
//获得根节点
var root = xhr.responseXML.documentElement;
var data = "";
var names = root.getElementsByTagName("Name");
var ages = root.getElementsByTagName("Age");
var len = names.length;
for (var i = 0; i < len; i++) {
data += "姓名:";
data += names[i].firstChild.nodeValue;
data += " 年龄:";
data += ages[i].firstChild.nodeValue;
data += " ";
}
console.log(data)
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
}
loadXML("info.xml");
</script>
如果你直接打开你的 html 文件,可能会在 console 里看到下面报错:
URL scheme must be "http" or "https" for CORS request.
Access to XMLHttpRequest at 'file:///.../info.xml' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
说明出现了跨域请求的问题。
使用 Apache 或 Nginx 启动一个 Web 服务,这样就不会出现跨域请求了。