본문 바로가기

JavaScript/XML

XML파일 값을 읽어서 테이블에 표시하기

반응형

bookXML.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8" ?>
<readBooks>
  <book>
    <title>나무</title>
    <author>베르나르베르베르</author>
    <price>11520</price>
  </book>
  <book>
    <title>지쳤거나 좋아하는 게 없거나</title>
    <author>강한별</author>
    <price>12150</price>
  </book>
  <book>
    <title>오늘도 펭수 내일도 펭수</title>
    <author>펭수</author>
    <price>15300</price>
  </book>
  <book>
    <title>좋은 날이야, 네가 옆에 있잖아</title>
    <author>이규영 </author>
    <price>11700</price>
  </book>
</readBooks>
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>

<body>
    <p id="pid"> </p>

    <table border="1">
        <thead>
            <th>제목</th>
            <th>저자</th>
            <th>가격</th>
        </thead>
        <tbody>

        </tbody>
    </table>


    <script type="text/javascript">
        var xmlhttp = new XMLHttpRequest();

        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                jsonFunction(this);
            }
        }

        xmlhttp.open("GET", "bookXML.xml", true);
        xmlhttp.send();

        function jsonFunction(xml) {
            var xmlDoc = xml.responseXML;
            // var arr = JSON.parse(resp);
            // var txt = "";
            var titleTag = xmlDoc.getElementsByTagName("title");

            for (i = 0; i < titleTag.length; i++) {
                /* var title = arr[i].title;
                var author = arr[i].author;
                var price = arr[i].price; */

                var title = xmlDoc.getElementsByTagName("title")[i].innerHTML;
                var author = xmlDoc.getElementsByTagName("author")[i].innerHTML;
                var price = xmlDoc.getElementsByTagName("price")[i].innerHTML;

                var thTitle = document.createTextNode(title);
                var tdAuthor = document.createTextNode(author);
                var tdPrice = document.createTextNode(price);
                var tr = document.createElement("tr");
                var th = document.createElement("th");
                var td1 = document.createElement("td");
                var td2 = document.createElement("td");

                th.appendChild(thTitle);
                td1.appendChild(tdAuthor);
                td2.appendChild(tdPrice);

                tr.appendChild(th);
                tr.appendChild(td1);
                tr.appendChild(td2);

                var tbody = document.getElementsByTagName("tbody")[0];

                tbody.appendChild(tr);

            }

        };
    </script>
</body>

</html>

반응형

'JavaScript > XML' 카테고리의 다른 글

XML 파일 읽어오기  (0) 2020.01.15
XML 코드 정리  (0) 2020.01.15