XML Uygulamaları
Bu bölüm, XML, HTTP, DOM ve JavaScript kullanan bazı HTML uygulamalarını gösterir.
Kullanılan XML Belgesi
Bu bölümde "cd_catalog.xml" adlı XML dosyasını kullanacağız .
Bir HTML Tablosunda XML Verilerini Görüntüleme
Bu örnek, her bir <CD> öğesi arasında dolaşır ve bir HTML tablosunda <ARTIST> ve <TITLE> öğelerinin değerlerini görüntüler:
Örnek
<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>
JavaScript ve XML DOM kullanımı hakkında daha fazla bilgi için DOM Intro'ya gidin.
İlk CD'yi bir HTML div Öğesinde Görüntüle
Bu örnek, id="showCD" ile bir HTML öğesindeki ilk CD öğesini görüntülemek için bir işlev kullanır:
Örnek
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;
}
CD'ler Arasında Gezin
Yukarıdaki örnekte CD'ler arasında gezinmek için bir
next()
ve previous()
işlevi oluşturun:
Örnek
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);
}
}
CD'ye Tıklarken Albüm Bilgilerini Göster
Son örnek, kullanıcı bir CD'yi tıkladığında albüm bilgilerini nasıl gösterebileceğinizi gösterir:
Örnek
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;
}