본문 바로가기
HTML

39일차//XML// XML 실습1 (노드로 접근)

by aesup 2021. 3. 9.
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>
728x90