HTML
39일차//XML// 🧶3. xml 파일을 생성해 데이터작성 후 불러오기
aesup
2021. 3. 9. 13:04
728x90
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p id = "demo"></p>
<script type="text/javascript">
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
//nodeValFunc(this);//조건문의 this
//nodeNameFunc(this);
childNodeFunc(this);
}
}
xhttp.open("GET","member.xml",true);
xhttp.send();
function nodeValFunc(xml) {
let num, name;
let txt, numtxt, xmlDoc;
txt= numtxt = "";
xmlDoc = xml.responseXML;//문서를 물러옴
//responseXML 프로퍼티는 서버에 요청하여 응답으로 받은 데이터를 XML DOM 객체로 반환합니다.
//
console.log(xmlDoc);
num = xmlDoc.getElementsByTagName("번호");
name = xmlDoc.getElementsByTagName("이름");
console.log(num.length);
for ( i = 0; i < num.length; i++) {
//안가져옴 오류 찾기= 해결 도트를 안찍음
txt += num[i].childNodes[0].nodeValue + "<br>";
numtxt += name[i].childNodes[0].nodeValue +"<br>";
}
document.getElementById("demo").innerHTML = txt + numtxt;
}
function nodeNameFunc( xml ) {
let arr, xmlDoc, txt;
txt = "";
xmlDoc = xml.responseXML;
arr = xmlDoc.documentElement.childNodes;
for (var i = 0; i < arr.length; i++) {
if(arr[i].nodeType == 1){
//위 조건은 데이터가 있을때를 말함
txt += arr[i].nodeName + "<br>";
//node를 불러오는 코드
}
}
document.getElementById("demo").innerHTML = txt;
}
function childNodeFunc( xml ) {
let arr, xmlDoc, txt;
txt = "";
xmlDoc = xml.responseXML;
arr = xmlDoc.getElementsByTagName("고객")[0];
let len = arr.childNodes.length;
//alert(len);//고객으로 했을때 9로 출력 태그 하나씩 계산
let fchild = arr.firstChild;
for (var i = 0; i < len; i++) {
if(fchild.nodeType == 1){
txt += i + " " + fchild.nodeName + "<br>";
}
fchild = fchild.nextSibling;
//nextSibling : 다음 형제 노드
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<고객들>
<고객>
<번호>1</번호>
<이름>이수빈</이름>
<주소>서울시</주소>
<방문>2021/03/09</방문>
</고객>
<고객>
<번호>2</번호>
<이름>주지훈</이름>
<주소>서울시</주소>
<방문>2021/03/08</방문>
</고객>
<고객>
<번호>3</번호>
<이름>강동원</이름>
<주소>서울시</주소>
<방문>2021/03/07</방문>
</고객>
</고객들>
728x90