从外部 XML 填充 HTML table

Populating an HTML table from an external XML

我在使用 JS 从外部 XML 文档中获取数据时遇到了问题。到目前为止,我一直在关注 AJAX XML 的 w3schools 教程,但我 运行 遇到了我无法解决的问题。我有一个看起来像这样的 XML:

<root>
 <document-id>
    <author>Tom Riddle</autor>
    <title>abzy</title>
    <year>1995</year>
 </document-id>
 <document-id>
    <author>Tom Riddle</autor>
    <title>abzy</title>
 </document-id>
 <document-id>
    <author>Tom Riddle</autor>
    <year>1995</year>
 </document-id>
</root>

我想动态访问 XML 中的数据并在这样做时创建一个 table。它适用于所有文档共享的 DOM 元素,但一旦我包含年份或标题,它就会给我一个错误。我想这是因为树的某些部分的标签是空的。有没有办法忽略空标签,只在列中有值时才在列中写入内容? 感谢您的时间和知识。

这是关联的 HTML

<body>
    <header>
        <h1>Reading Data from XML Files</h1>
    </header>
    <main>

        <button type="button" onclick="loadDoc()">Get my CD collection</button>

        <table id="demo">

        </table>

    </main>   
    <script>
       function loadDoc() {
          const xhttp = new XMLHttpRequest();
          xhttp.onload = function() {
            myFunction(this);
          }
          xhttp.open("GET", "books.xml");
          xhttp.send();
        }
        function myFunction(xml) {
          const xmlDoc = xml.responseXML;
          const x = xmlDoc.getElementsByTagName("document-id");
          console.log(x)
          let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>"; 
          for (let i = 0; i <x.length; i++) { 
            table += "<tr><td>" +
            x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue +
            "</tr>";
          }
          document.getElementById("demo").innerHTML = table;
        }
    </script>
</body>

在尝试访问子项之前检查是否存在。

function getText(node, tag) {
  var elem = node.getElementsByTagName(tag);
  return elem ? elem.[0].childNodes[0].nodeValue : '';
}

for (let i = 0; i <x.length; i++) { 
    var cells = ['author', 'title', 'year'].map(function (tag) {
      return "<td>" + getText(x[i], tag) + "</td>";
    }).join("");

    table += "<tr>" + cells + "</tr>");
}

尝试使用在线解决方案来检查 xml

中是否存在标签
function myFunction(xml) {
      const xmlDoc = xml.responseXML;
      const x = xmlDoc.getElementsByTagName("document-id");
      console.log(x)
      let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>"; 
     
     for (let i = 0; i <x.length; i++) { 
        table += "<tr><td>" +
        x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
         "</td><td>" +   ((x[i].getElementsByTagName("title")[0] == undefined)?"": x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue )    +
        "</td><td>" +
      ((x[i].getElementsByTagName("year")[0] == undefined)?"": x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue )    +
        "</tr>";
      }
      
      document.getElementById("demo").innerHTML = table;
    }