XML 애플리케이션
이 장에서는 XML, HTTP, DOM 및 JavaScript를 사용하는 일부 HTML 응용 프로그램을 보여줍니다.
사용된 XML 문서
이 장에서는 "cd_catalog.xml" 이라는 XML 파일을 사용합니다 .
HTML 테이블에 XML 데이터 표시
이 예는 각 <CD> 요소를 반복하고 HTML 테이블에 <ARTIST> 및 <TITLE> 요소의 값을 표시합니다.
예시
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse:collapse;
}
th, td {
padding: 5px;
}
</style>
</head>
<body>
<button type="button" onclick="loadXMLDoc()">Get my CD collection</button>
<br><br>
<table id="demo"></table>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange =
function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "cd_catalog.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length;
i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue
+
"</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue
+
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
JavaScript 및 XML DOM 사용에 대한 자세한 내용은 DOM 소개를 참조하십시오.
HTML div 요소에 첫 번째 CD 표시
이 예에서는 id="showCD"인 HTML 요소의 첫 번째 CD 요소를 표시하는 함수를 사용합니다.
예시
displayCD(0);
function displayCD(i) {
var xmlhttp
= new XMLHttpRequest();
xmlhttp.onreadystatechange =
function() {
if (this.readyState
== 4 && this.status == 200) {
myFunction(this, i);
}
};
xmlhttp.open("GET", "cd_catalog.xml", true);
xmlhttp.send();
}
function myFunction(xml, i) {
var xmlDoc = xml.responseXML;
x =
xmlDoc.getElementsByTagName("CD");
document.getElementById("showCD").innerHTML =
"Artist: "
+
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue
+
"<br>Title: " +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue
+
"<br>Year: " +
x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
CD 간 탐색
CD 사이를 탐색하려면 위의 예에서 next() 및 previous() 함수를 추가하십시오.
예시
function next()
{
// display the next CD, unless you are on the last CD
if (i < x.length-1) {
i++;
displayCD(i);
}
}
function previous()
{
// display the previous CD, unless you are on the first CD
if (i > 0) {
i--;
displayCD(i);
}
}
CD를 클릭하면 앨범 정보 표시
마지막 예는 사용자가 CD를 클릭할 때 앨범 정보를 표시하는 방법을 보여줍니다.
예시
function displayCD(i) {
document.getElementById("showCD").innerHTML
=
"Artist: " +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue
+
"<br>Title: " +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue
+
"<br>Year: " +
x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}