You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript遍历XML节点并输出HTML表格

Solution: Generate HTML Table from XML with JavaScript

Got it, let's work through this. You need to build an HTML table where each node in your Books.xml becomes a table row, and can't use XSLT—totally understandable. Let's expand on your existing code snippet to make this robust and functional.

First, let's assume your Books.xml has a structure like this (adjust this to match your actual XML nodes):

<Books>
  <Book>
    <Title>The Great Gatsby</Title>
    <Author>F. Scott Fitzgerald</Author>
    <Year>1925</Year>
  </Book>
  <Book>
    <Title>1984</Title>
    <Author>George Orwell</Author>
    <Year>1949</Year>
  </Book>
</Books>

Here's the complete, improved JavaScript code to fetch the XML and build your table:

// Create XMLHttpRequest object (handle browser compatibility)
let xmlhttp;
if (window.XMLHttpRequest) {
  // Modern browsers (IE7+, Firefox, Chrome, Opera, Safari)
  xmlhttp = new XMLHttpRequest();
} else {
  // Older IE versions
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

// Fetch the XML file asynchronously (blocks less than sync requests)
xmlhttp.open("GET", "Books.xml", true);
xmlhttp.onreadystatechange = function() {
  // Only proceed if request is complete and successful
  if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
    const xmlDoc = xmlhttp.responseXML;
    buildBookTable(xmlDoc);
  }
};
xmlhttp.send();

// Function to construct the table from XML data
function buildBookTable(xml) {
  // Grab all <Book> nodes from the XML
  const bookNodes = xml.getElementsByTagName("Book");
  
  // Create the table element and add styling/ID
  const table = document.createElement("table");
  table.id = "bookTable";
  table.style.borderCollapse = "collapse"; // Clean up borders
  
  // Create header row
  const headerRow = document.createElement("tr");
  const headerLabels = ["Title", "Author", "Year"]; // Match your XML child node names
  headerLabels.forEach(label => {
    const th = document.createElement("th");
    th.textContent = label;
    th.style.border = "1px solid #ddd";
    th.style.padding = "8px";
    th.style.backgroundColor = "#f2f2f2";
    headerRow.appendChild(th);
  });
  table.appendChild(headerRow);
  
  // Loop through each <Book> node to create a table row
  for (let i = 0; i < bookNodes.length; i++) {
    const row = document.createElement("tr");
    
    // Extract data from each child node (add checks to avoid errors if nodes are missing)
    const title = bookNodes[i].getElementsByTagName("Title")[0]?.textContent || "N/A";
    const author = bookNodes[i].getElementsByTagName("Author")[0]?.textContent || "N/A";
    const year = bookNodes[i].getElementsByTagName("Year")[0]?.textContent || "N/A";
    
    // Create table cells and populate with data
    const cellValues = [title, author, year];
    cellValues.forEach(value => {
      const td = document.createElement("td");
      td.textContent = value;
      td.style.border = "1px solid #ddd";
      td.style.padding = "8px";
      row.appendChild(td);
    });
    
    table.appendChild(row);
  }
  
  // Add the finished table to your page (replace with your target element ID)
  document.getElementById("tableContainer").appendChild(table);
}

Key Improvements & Notes:

  • Asynchronous Request: Swapped false to true in xmlhttp.open()—sync requests block the browser, which hurts user experience.
  • Avoid document.write: Instead of using document.write (which can overwrite your entire page if called after load), we build DOM elements dynamically and append them to a container in your HTML.
  • Error Resilience: Added optional chaining (?.) and fallback values (|| "N/A") to handle cases where a node might be missing from your XML.
  • Basic Styling: Added inline styles to make the table readable—you can move these to a CSS file for cleaner code.

Setup in Your HTML:

Add a container where the table will be inserted:

<div id="tableContainer"></div>

Wrap your JavaScript in a DOMContentLoaded listener to ensure the container exists before the code runs:

document.addEventListener("DOMContentLoaded", function() {
  // Place the XML request code here
});

内容的提问来源于stack exchange,提问作者shetaan819

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:57:24