缺少XML DOM中的节点 - 简单示例

时间:2016-07-23 15:37:18

标签: javascript html xml dom

How the XML table should render

不会呈现,因为.XML文档在UNIT 3中缺少QUANTITY的节点。

我们如何跳过XML DOM中缺少的节点?


XML doc(example.xml)

<?xml version="1.0" encoding="UTF-8"?>
<CUSTOMER_ORDER>
    <UNIT>
        <ID>Unit 1</ID>
        <QUANTITY>45</QUANTITY>
        <PRICE>25.99</PRICE>
    </UNIT>
    <UNIT>
        <ID>Unit 2</ID>
        <QUANTITY>209</QUANTITY>
        <PRICE>9.95</PRICE>
    </UNIT>
    <UNIT>
        <ID>Unit 3</ID>   <!-- The QUANTITY node for Unit 3 is missing -->
        <PRICE>14.99</PRICE>
    </UNIT>
    <UNIT>
        <ID>Unit 4</ID>
        <QUANTITY>156</QUANTITY>
        <PRICE>35.88</PRICE>
    </UNIT>
    <UNIT>
        <ID>Unit 5</ID>
        <QUANTITY>25</QUANTITY>
        <PRICE>199.00</PRICE>
    </UNIT>
</CUSTOMER_ORDER>

这是XML DOM(带有HTML)

<!DOCTYPE html>
<html>
<style>
table,th,td {
  border : 2px solid black;
  border-collapse: collapse;
}
th,td {
  padding: 5px;
}
</style>
<body>

<body onload="loadXMLDoc()">

<table id="test"></table>

<script>
function loadXMLDoc() {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
     testFunction(xmlhttp);
    }
  };
  xmlhttp.open("GET", "example.xml", true);
  xmlhttp.send();
}
function testFunction(xml) {
  var table="<tr><th>Unit</th><th>Price</th><th>Quantity</th></tr>";
  var xmlDoc = xml.responseXML;
  var i;
  var y = xmlDoc.getElementsByTagName("UNIT");
  for (i = 0; i < y.length; i++) 
  {
  var u = y[i].getElementsByTagName("ID")[0].childNodes[0].nodeValue;
  var p = y[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue;
  var q = y[i].getElementsByTagName("QUANTITY")[0].childNodes[0].nodeValue;

    table += "<tr><td>" +
    u +                         // Unit ID column
    "</td><td>" +
    p +                         // PRICE column
    "</td><td>" +
    q +                         // QUANTITY column
    "</td></tr>";
   }
  document.getElementById("test").innerHTML = table;
}
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

与@Pointy一样,如果 QUANTITY 缺失,请在设置 q 之前检查是否有数量,然后将默认设置为1或任何您想要的值。

替换它:

var q = y[i].getElementsByTagName("QUANTITY")[0].childNodes[0].nodeValue;

with:

var qElem = y[i].getElementsByTagName("QUANTITY"); //Get quantity elems
var q = (qElem.length > 0) ? qElem[0].childNodes[0].nodeValue : 1; //Check if there is anything in qElem if not set q to 1

这应该有用。