Aplicaciones XML
Este capítulo muestra algunas aplicaciones HTML que utilizan XML, HTTP, DOM y JavaScript.
El documento XML utilizado
En este capítulo utilizaremos el archivo XML denominado "cd_catalog.xml" .
Mostrar datos XML en una tabla HTML
Este ejemplo recorre cada elemento <CD> y muestra los valores de los elementos <ARTIST> y <TITLE> en una tabla HTML:
Ejemplo
<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>
Para obtener más información sobre el uso de JavaScript y XML DOM, vaya a DOM Intro.
Mostrar el primer CD en un elemento HTML div
Este ejemplo usa una función para mostrar el primer elemento de CD en un elemento HTML con id="showCD":
Ejemplo
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;
}
Navegar entre los CD
Para navegar entre los CD en el ejemplo anterior, cree una
función next()
y previous()
:
Ejemplo
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);
}
}
Mostrar información del álbum al hacer clic en un CD
El último ejemplo muestra cómo puede mostrar la información del álbum cuando el usuario hace clic en un CD:
Ejemplo
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;
}