• 코드:
​x
 
1
<!DOCTYPE html>
2
<html lang="ko">
3
​
4
<head>
5
    <meta charset="UTF-8">
6
    <title>XML Node</title>
7
    <script>
8
        function loadDoc() {
9
            var xmlHttp = new XMLHttpRequest();
10
            xmlHttp.onreadystatechange = function() {
11
                if(this.status == 200 && this.readyState == this.DONE) {
12
                    createNode(xmlHttp);
13
                }
14
            };
15
            xmlHttp.open("GET", "/examples/media/programming_languages.xml", true);
16
            xmlHttp.send();
17
        }
18
​
19
        function createNode(xmlHttp) {
20
            var xmlObj, thirdLang, newNode, newTextNode, node, result, idx;
21
            xmlObj = xmlHttp.responseXML;   // 요청한 데이터를 XML DOM 객체로 반환함.
22
            thirdLang = xmlObj.getElementsByTagName("language")[2]; // 세 번째 <language>요소를 반환함.
23
​
24
            // 변경 전
25
            node = thirdLang.firstChild;
26
            result = "변경 전 : <br>";
27
            for(idx = 0; idx < thirdLang.childNodes.length; idx++) {
28
                if(node.nodeType == 1) {
29
                    result += node.nodeName + " : " + node.firstChild.nodeValue + "<br>";
30
                }
31
                node = node.nextSibling;
32
            }
33
            
34
            newNode = xmlObj.createElement("paradigm");         // 새로운 <paradigm>요소를 생성함.
35
            newTextNode = xmlObj.createTextNode("객체 지향");   // 새로운 텍스트 노드를 생성함.
36
            newNode.appendChild(newTextNode);                   // <paradigm>요소에 텍스트 노드를 추가함.
37
            thirdLang.appendChild(newNode);                     // 세 번째 <language>요소에 새로운 요소를 추가함.
38
            
39
            // <language>요소의 자식 요소 노드를 모두 출력함.
40
            node = thirdLang.firstChild;
41
            result += "<br>변경 후 : <br>";
42
            for(idx = 0; idx < thirdLang.childNodes.length; idx++) {
43
                if(node.nodeType == 1) {
44
                    result += node.nodeName + " : " + node.firstChild.nodeValue + "<br>";
45
                }
46
                node = node.nextSibling;
47
            }
48
            document.getElementById("text").innerHTML = result;
49
        }
50
    </script>
51
</head>
52
​
53
<body>
54
​
55
    <h1>노드의 생성</h1>
56
    <button onclick="loadDoc()">텍스트 노드 생성!</button>
57
    <p id="text"></p>
58
    
59
</body>
60
​
61
</html>