提问人:Niamh13 提问时间:10/27/2023 最后编辑:Tony GrahamNiamh13 更新时间:11/18/2023 访问量:62
在 html 表上显示 xml 数据
Displaying xml data on a html table
问:
我正在尝试将数据从 xml 文件显示到带有 xsl 和 JavaScript 文件的 html 文件。我正在使用 Apache NetBeans。我还希望包括我的每个书籍元素的图像,这些图像也将被带到桌面上。如果有人有任何其他想法,请帮忙
我的文件是 books.xml、booksStyle.xsl、index.html 和 script.js。我还有一个架构。
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="booksStyle.xsl"?>
<catalog>
<book id="1">
<name>I Know You Did It</name>
<genre>Thriller</genre>
<description>On her first day at a new school, Ruby finds a note in her locker saying I Know You Did It. She's terrified that someone has found out she was responsible for the death of a girl called Hannah in a playground when they were both toddlers – a secret she has been keeping guiltily for ten years.</description>
<code>156-05</code>
<quantity>56</quantity>
<price>7.99</price>
</book>
<book id="2">
<name>Robin Williams, when the Laughter Stops</name>
<genre>Biography</genre>
<description>When the Laughter Stops," examines this brutal and tragic dichotomy, casting its incisive eye on the comedians' personal lives, while separating fact from fiction, creative work from the human being behind it, to probe not just from where their genius sprung - but how that same wellspring often lead to their demise.</description>
<code>145-04</code>
<quantity>13</quantity>
<price>12.59</price>
</book>
<book id="3">
<name>Invisible Girl</name>
<genre>Psychological Fiction</genre>
<description>Saffyre Maddox has been suffering the aftermath of a traumatizing incident for over 8 years. She is self-harming and her guardian-uncle sends her to therapy.</description>
<code>056-06</code>
<quantity>120</quantity>
<price>8.99</price>
</book>
<book id="4">
<name>The Golden Ass</name>
<genre>Picaresque Novel</genre>
<description>The Metamorphoses of Apuleius, which Augustine of Hippo referred to as The Golden Ass, is the only ancient Roman novel in Latin to survive in its entirety. The protagonist of the novel is Lucius. At the end of the novel, he is revealed to be from Madaurus, the hometown of Apuleius himself.</description>
<code>020-08</code>
<quantity>42</quantity>
<price>18.19</price>
</book>
<book id="5">
<name>Four Seasons in Japan</name>
<genre>Coming-of-age</genre>
<description>It is a story about Ayako, a fierce and strict old woman who runs a coffee shop in the small town of Onomichi, where she has just taken guardianship of her grandson, Kyo. Haunted by long-buried family tragedy, both have suffered extreme loss and feel unable to open up to each other.</description>
<code>304-03</code>
<quantity>34</quantity>
<price>16.38</price>
</book>
<book id="6">
<name>Can You Keep a Secret?</name>
<genre>Crime Fiction</genre>
<description>Lindsey hasn't spoken to Rachel in twenty years, not since her brother's 18th birthday party at their parents' remote country house. A night that shattered so many friendships – and left Rachel's father dead. Now Thornbury Hall is up for sale, and the old gang are back there, together again.</description>
<code>150-02</code>
<quantity>61</quantity>
<price>10.36</price>
</book>
<book id="7">
<name>To Sleep In a Sea of Stars</name>
<genre>Science Fiction</genre>
<description>During a routine survey mission on an uncolonized planet, Kira finds an alien relic. At first she's delighted, but elation turns to terror when the ancient dust around her begins to move. As war erupts among the stars, Kira is launched into a galaxy-spanning odyssey of discovery and transformation.</description>
<code>145.02</code>
<quantity>30</quantity>
<price>14.55</price>
</book>
<book id="8">
<name>Tokyo Ever After</name>
<genre>Fiction</genre>
<description>Tokyo Ever After follows Izumi, a normal Asian girl who has found a home in her small group of Asian girlfriends in a town that is almost entirely white. While trying to find out more information about her father, one of Izumi's friends finds him, but he is not what they expect.</description>
<code>054-02</code>
<quantity>24</quantity>
<price>11.19</price>
</book>
<book id="9">
<name>Forgotten Women: The Scientists</name>
<genre>Biography</genre>
<description>The Scientists celebrates 48* unsung heroines whose hugely important, yet broadly unacknowledged or incorrectly attributed, discoveries have transformed our understanding of the scientific world. *The number of Nobel-prize-winning women.</description>
<code>065-04</code>
<quantity>67</quantity>
<price>13.60</price>
</book>
<book id="10">
<name>Yellowface</name>
<genre>Psychological Fiction</genre>
<description>June Hayward and her friend Athena Liu, a Chinese-American author who has been working on a book about Chinese laborers in World War I. Following Athena's untimely death, June steals her manuscript and attempts to build up her career through Athena's work.</description>
<code>157-06</code>
<quantity>34</quantity>
<price>13.99</price>
</book>
</catalog>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html>
<head>
<title>Style</title>
</head>
<body>
<xsl:for-each select="catalog/book">
<xsl:value-of select="name"/>
<xsl:value-of select="genre"/>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script scr="script.js"></script>
</head>
<body>
<table id = "book_data">
<tr><th>Name</th><th>Genre</th><th>Description</th><th>Code</th><th>Quantity</th><th>Price</th>
</tr>
</table>
</body>
</html>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "books.xml",
dataType: "xml",
complete: function(xml){
console.log(xml);
$(xml).find('catalog/book').each(function(){
var name = $(this).find('name').text();
var genre = $(this).find('genre').text();
var description = $(this).find('description').text();
$('<tr></tr>').html('<th>' +name+ '</th><td>$' +genre+ '</td><td>$' +description+ '</td>').appendTo('#book_data');
});
},
});
});
我尝试在我的 JavaScript 中使用 ajax 来显示,没有出现错误,但没有显示数据。我还尝试使用 XSLT 进行显示,但 xml 版本和编码声明出现错误。
答:
0赞
Mahmud Hasan
10/27/2023
#1
请尝试下面的代码,它对我来说没问题。检查随附的图像。我建议您根据需要添加自己的 css 和图像序列。谢谢
<!DOCTYPE html>
<html>
<head>
<title>Book Catalog</title>
<!-- Link to the external CSS file -->
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
function loadXMLDoc() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "books.xml", false);
xhttp.send("");
return xhttp.responseXML;
}
function loadXSLDoc() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "booksStyle.xsl", false); // Make sure the XSLT file is named "booksStyle.xsl"
xhttp.send("");
return xhttp.responseXML;
}
function displayCatalog() {
var xml = loadXMLDoc();
var xsl = loadXSLDoc();
if (xml && xsl) {
try {
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
var resultDocument = xsltProcessor.transformToFragment(xml, document);
if (resultDocument) {
document.getElementById("catalog").appendChild(resultDocument);
} else {
console.error("Result document is not valid.");
}
} catch (error) {
console.error("Error during XSLT transformation:", error);
}
} else {
console.error("XML or XSLT document not loaded.");
}
}
</script>
</head>
<body onload="displayCatalog()">
<div id="catalog"></div>
</body>
</html>
评论
0赞
Niamh13
10/29/2023
该代码似乎不适用于 Netbeans 或记事本++。你用什么应用程序来运行它?
0赞
Mahmud Hasan
10/29/2023
你需要在服务器下运行它,我建议你使用 Xampp、Wampp 或 Laragon。
0赞
ThW
11/18/2023
#2
您的 XSL 只是缺少 HTML 元素,但它可以工作。
对于纯 JavaScript 变体 - 现代浏览器具有异步功能。对于 XML,您可以将其包装到自己的异步函数中:fetch()
async function fetchXML(url) {
// asynchronous functions can wait for other async calls
// so fetch the url, read the response as text and parse into a DOM
return (new DOMParser()).parseFromString(
await(
await fetch(url)
).text(),
'application/xml'
);
}
CSS 选择器可用于对 HTML 文档中的元素进行寻址,以及 XML 文档。以下示例在 HTML 文档,并为每本书克隆它。
// call the load function and catch errors
loadBooks('./books.xml').catch((e) => console.log(e));
// define an asynchronous load function
async function loadBooks(url) {
// fetch the template structure from the document
const template = document.querySelector('[data-template-for=book]');
delete template.dataset.templateFor;
// store some context
const container = template.parentNode;
const nextElement = template.nextElementSibling;
// remove template from document
template.remove();
const books = await fetchXML(url);
// iterate the book elements (use CSS selectors to fetch them)
books.querySelectorAll('catalog > book').forEach(
(book) => {
const row = template.cloneNode(true);
// iterate the template cells
row.querySelectorAll('[data-field]').forEach(
(cell) => {
// and fill them
cell.textContent = book.querySelector(cell.dataset.field)?.textContent || '';
}
);
container.insertBefore(row, nextElement);
}
);
}
// simulate the XML fetch
async function fetchXML(url) {
const data = `<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<book id="1">
<name>I Know You Did It</name>
<genre>Thriller</genre>
<description>On her first day at a new school, Ruby finds a note in her locker saying I Know You Did It. She's terrified that someone has found out she was responsible for the death of a girl called Hannah in a playground when they were both toddlers – a secret she has been keeping guiltily for ten years.</description>
<code>156-05</code>
<quantity>56</quantity>
<price>7.99</price>
</book>
<book id="2">
<name>Robin Williams, when the Laughter Stops</name>
<genre>Biography</genre>
<description>When the Laughter Stops," examines this brutal and tragic dichotomy, casting its incisive eye on the comedians' personal lives, while separating fact from fiction, creative work from the human being behind it, to probe not just from where their genius sprung - but how that same wellspring often lead to their demise.</description>
<code>145-04</code>
<quantity>13</quantity>
<price>12.59</price>
</book>
<book id="3">
<name>Invisible Girl</name>
<genre>Psychological Fiction</genre>
<description>Saffyre Maddox has been suffering the aftermath of a traumatizing incident for over 8 years. She is self-harming and her guardian-uncle sends her to therapy.</description>
<code>056-06</code>
<quantity>120</quantity>
<price>8.99</price>
</book>
</catalog>`;
return (new DOMParser()).parseFromString(data, 'application/xml');
}
<html lang="en">
<head>
<title>Books</title>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Genre</th>
</tr>
<tr data-template-for="book">
<td data-field="name"></td>
<td data-field="genre"></td>
</tr>
</table>
</body>
</html>
评论