HTML
XML / <자신이 읽은 책 5권을 XML파일로 제작후 테이블로 시각화 하기>
aesup
2021. 3. 9. 20:05
728x90
XML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 자신이 읽은 책 :5권
제목(title), 저자 (author), 가격(price
parsing 데이터
시각화-> 테이블
-->
<div id="books"></div>
<script type="text/javascript">
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
nodeValFunc(this);
}
}
xhttp.open("GET","xmlBook.xml",true);
xhttp.send();
function nodeValFunc(xml) {
let num, name;
let txt, numtxt, xmlDoc;
txt= numtxt = "";
xmlDoc = xml.responseXML;//문서를 물러옴
//root tag 값 가져오기
let rootTagName = xmlDoc.documentElement.nodeName;
//alert(rootTagName);
// node명을 취득
let nodeArr = xmlDoc.documentElement.childNodes;
//alert(nodeArry);
//node list 를 모두 확인한다
let nodeName;
for (var i = 0; i < nodeArr.length; i++) {
if(nodeArr[i].nodeType == 1){
nodeName =nodeArr[i].nodeName;
//alert(nodeName);
}
}
//table제작
//문자열 생성
let tableOut = "<table border = '1'>";
tableOut += "<col width='100'><col width='100'><col width='140'><col width='100'>";
tableOut += "<tr>";
tableOut += "<th>책번호</th>";
//column명
let columName = xmlDoc.getElementsByTagName("book")[0];
let len = columName.childNodes.length;
let fchild = columName.firstChild;
//alert(len); 7개
//alert(columName);
for (var i = 0; i < columName.childNodes.length; i++) {
if(fchild.nodeType == 1){
//위 조건은 데이터가 있을때를 말함
tableOut += "<th>"+ fchild.nodeName + "</th>";
//alert(fclild.nodeName);
}
fchild = fchild.nextSibling;
}
tableOut += "</tr>"
let leng = xmlDoc.getElementsByTagName(nodeName).length;
alert(leng);
for (var i = 0; i < leng; i++) {
tableOut += "<tr>";
tableOut += "<th>" + (i + 1) + "</th>";
//책들을 가져온다.
//한꺼번에 가져온다.
let dataArr = xmlDoc.getElementsByTagName(nodeName)[i];
fchild = dataArr.firstChild;
for ( j = 0; j < dataArr.childNodes.length; j++) {
if (fchild.nodeType == 1) {
tableOut += "<td>" + fchild.childNodes[0].nodeValue + "</td>";
}
fchild =fchild.nextSibling;
}
tableOut += "</tr>";
}
tableOut += "</table>";
document.getElementById("books").innerHTML = tableOut;
}
</script>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book>
<title>자바의 정석</title>
<author>남궁성</author>
<price>20,000</price>
</book>
<book>
<title>테슬라 모터스</title>
<author>찰리모리스</author>
<price>25,000</price>
</book>
<book>
<title>슈퍼개미 김정환에게 배우는 나의 첫 투자 수업</title>
<author>김정환</author>
<price>30,000</price>
</book>
<book>
<title>주린이가 가장 알고싶은 최다질문</title>
<author>염승환</author>
<price>16,200</price>
</book>
<book>
<title>언어의온도</title>
<author>이수만</author>
<price>20,000</price>
</book>
</bookstore>
728x90