• 코드:
​x
 
1
<!DOCTYPE html>
2
<html lang="ko">
3
​
4
<head>
5
    <meta charset="UTF-8">
6
    <title>XML INTRO</title>
7
    <style>
8
        table, th, td {
9
            border: 1px solid black;
10
            border-collapse: collapse;
11
        }
12
    </style>
13
    <script>
14
        function loadDoc() {
15
            var xmlHttp = new XMLHttpRequest();
16
            xmlHttp.onreadystatechange = function() {
17
                if(this.status == 200 && this.readyState == this.DONE) {
18
                    displayData(xmlHttp);
19
                }
20
            };
21
            xmlHttp.open("GET", "/examples/media/korean_major_cities.xml", true);
22
            xmlHttp.send();
23
        }
24
​
25
        function displayData(xmlHttp) {
26
            var xmlObj, cityList, result, idx;
27
            xmlObj = xmlHttp.responseXML;   // 요청한 데이터를 XML DOM 객체로 반환함.
28
            result = "<table><tr><th>도시 이름</th><th>행정구역</th></tr>";
29
            cityList = xmlObj.getElementsByTagName("city");
30
            for(idx = 0; idx < cityList.length; idx++) {
31
                result += "<tr><td>" + 
32
                    cityList[idx].getElementsByTagName("name")[0].childNodes[0].nodeValue + "</td><td>" +
33
                    cityList[idx].getElementsByTagName("class")[0].childNodes[0].nodeValue + "</td></tr>";
34
            }
35
            result += "</table>";
36
            document.getElementById("text").innerHTML = result;
37
        }
38
    </script>
39
</head>
40
​
41
<body>
42
​
43
    <h1>HTML로부터 데이터 분리</h1>
44
    <button onclick="loadDoc()">XML 데이터 불러오기!</button>
45
    <p id="text"></p>
46
    
47
</body>
48
​
49
</html>