我有这段代码来解析 XML。我将如何处理 XML 中的空节点?目前,“v2”节点为空,根本没有输出...
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "sample.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>c1</th><th>c2</th></tr>";
var x = xmlDoc.getElementsByTagName("product");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("v1")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("v2")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
XML:
<products>
<product>
<v1>some data</v1>
<v2/>
</product>
</products>
最佳答案
简单地检查它是否不为空然后使用数据,否则就跳过它。
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", `data:text/xml,<products>
<product>
<v1>some data</v1>
<v2/>
</product>
</products>`, true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>c1</th><th>c2</th></tr>";
var x = xmlDoc.getElementsByTagName("product");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("v1")[0].childNodes[0].nodeValue + "</td><td>";
var v2c = x[i].getElementsByTagName("v2")[0].childNodes;
if (v2c.length > 0){
table += v2c[0].nodeValue;
}
table += "</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
<button onclick="loadDoc()">Load</button>
<table id="demo" border="1"></table>
关于javascript - 通过 AJAX 处理 XML 中的空节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49885308/