Applicazioni XML
Questo capitolo illustra alcune applicazioni HTML che utilizzano XML, HTTP, DOM e JavaScript.
Il documento XML utilizzato
In questo capitolo useremo il file XML chiamato "cd_catalog.xml" .
Visualizza i dati XML in una tabella HTML
Questo esempio scorre ogni elemento <CD> e mostra i valori degli elementi <ARTIST> e <TITLE> in una tabella HTML:
Esempio
<table id="demo"></table>
<script>
function loadXMLDoc() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const xmlDoc = xml.responseXML;
const cd = xmlDoc.getElementsByTagName("CD");
myFunction(cd);
}
xmlhttp.open("GET", "cd_catalog.xml");
xmlhttp.send();
}
function myFunction(cd) {
let table="<tr><th>Artist</th><th>Title</th></tr>";
for (let i = 0; i < cd.length; i++) {
table += "<tr><td>" +
cd[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue
+
"</td><td>" +
cd[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue
+
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
Per ulteriori informazioni sull'utilizzo di JavaScript e del DOM XML, vai a DOM Intro.
Visualizza il primo CD in un elemento div HTML
Questo esempio usa una funzione per visualizzare il primo elemento CD in un elemento HTML con id="showCD":
Esempio
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
const xmlDoc = xhttp.responseXML;
const cd = xmlDoc.getElementsByTagName("CD");
myFunction(cd, 0);
}
xhttp.open("GET", "cd_catalog.xml");
xhttp.send();
function myFunction(cd, i) {
document.getElementById("showCD").innerHTML =
"Artist: " +
cd[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"<br>Title: " +
cd[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"<br>Year: " +
cd[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
Naviga tra i CD
Per navigare tra i CD nell'esempio sopra, creare una
funzione next()
e previous()
:
Esempio
function next()
{
// display the next CD, unless you are on the last CD
if (i < len-1) {
i++;
displayCD(i);
}
}
function previous()
{
// display the previous CD, unless you are on the first CD
if (i > 0) {
i--;
displayCD(i);
}
}
Mostra le informazioni sull'album quando si fa clic su un CD
L'ultimo esempio mostra come mostrare le informazioni sull'album quando l'utente fa clic su un CD:
Esempio
function displayCD(i) {
document.getElementById("showCD").innerHTML =
"Artist: " +
cd[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"<br>Title: " +
cd[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"<br>Year: " +
cd[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}