HTML 中的 XML
使用 JavaScript 在 HTML 中显示 XML 数据
Section titled “使用 JavaScript 在 HTML 中显示 XML 数据”一个常见的任务是获取 XML 数据并将其动态地显示在 HTML 页面中。现代 JavaScript 提供了高效的方式来实现这一点。
在这个例子中,我们将获取一个包含音乐 CD 列表的 XML 文件(cd_catalog.xml)。然后,我们将解析(parse)该 XML,并在 HTML 表格中显示每张 CD 的 Artist(艺术家)和 Title(标题)。
假设 cd_catalog.xml 文件大致如下所示:
<CATALOG> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> <YEAR>1985</YEAR> </CD> <CD> <TITLE>Hide your heart</TITLE> <ARTIST>Bonnie Tyler</ARTIST> <YEAR>1988</YEAR> </CD> ...</CATALOG>以下是 HTML 和 JavaScript 代码:
<!DOCTYPE html><html><head><title>XML to HTML Example</title><style> table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 8px; text-align: left; } th { background-color: #f2f2f2; }</style></head><body>
<h1>CD Catalog</h1><table id="cdTable"> <thead> <tr> <th>Artist</th> <th>Title</th> </tr> </thead> <tbody> <!-- CD data will be inserted here by JavaScript --> </tbody></table>
<script> // Function to fetch and display XML data async function displayCatalog() { const tableBody = document.querySelector("#cdTable tbody"); tableBody.innerHTML = ''; // Clear existing table content
try { // 1. Fetch the XML file const response = await fetch('cd_catalog.xml'); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const xmlText = await response.text();
// 2. Parse the XML string const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlText, "application/xml");
// Check for parsing errors (optional but recommended) const parseError = xmlDoc.querySelector('parsererror'); if (parseError) { console.error('Error parsing XML:', parseError); tableBody.innerHTML = '<tr><td colspan="2">Error loading or parsing XML data.</td></tr>'; return; }
// 3. Select all CD elements const cds = xmlDoc.querySelectorAll("CD"); // Using querySelectorAll for modern selection
// 4. Iterate through each CD element cds.forEach(cd => { // Get ARTIST and TITLE values (using nullish coalescing for safety) const artist = cd.querySelector("ARTIST")?.textContent ?? 'N/A'; const title = cd.querySelector("TITLE")?.textContent ?? 'N/A';
// 5. Create new table row and cells const row = document.createElement("tr");
const artistCell = document.createElement("td"); artistCell.textContent = artist; row.appendChild(artistCell);
const titleCell = document.createElement("td"); titleCell.textContent = title; row.appendChild(titleCell);
// 6. Append the row to the table body tableBody.appendChild(row); });
} catch (error) { console.error('Failed to load or process CD catalog:', error); tableBody.innerHTML = `<tr><td colspan="2">Failed to load data: ${error.message}</td></tr>`; } }
// Call the function when the page loads document.addEventListener('DOMContentLoaded', displayCatalog);
</script>
</body></html>这种现代方法使用了:
fetchAPI: 用于发起异步网络请求(替代XMLHttpRequest)。async/await: 更清晰地处理异步操作。DOMParser: 将 XML(和 HTML)字符串解析为 DOM 结构的标准浏览器 API。- 标准 DOM 操作 (
querySelector,querySelectorAll,createElement,appendChild,textContent): 安全高效地构建 HTML 表格(替代document.write)。 - 错误处理 (
try...catch): 管理获取或解析过程中可能出现的问题。
要进行更高级的 JavaScript XML 操作,请进一步探索 XML DOM (Document Object Model) 接口。