본문 바로가기
📚 개발 공부

[Javascript ] responseXML로 XML 응답 읽어오기 예제

by cheonvi 2009. 11. 28.

<SCRIPT LANGUAGE="JavaScript">
<!--

var httpRequest =null;
 function getXMLHttpRequest(){
  if (window.ActiveXObject){
   try{
    return new ActiveXObject("Msxml2.XMLHTTP");
   } catch(e){
    try{
      return new ActiveXObject("Microsoft.XMLHTTP");
     } catch(e1){
      return null;
     }
    }
  } else if (window.XMLHttpRequest){
   return new XMLHttpRequest();
  } else {
   return null;
  }
}

function load(url) {

 

 httpRequest = getXMLHttpRequest();
 httpRequest.onreadystatechange = viewMessage;
 httpRequest.open("Get",url,true);
// httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 httpRequest.send(null);

}

function viewMessage()
{
var str_option=""
 if (httpRequest.readyState==4) {
  if (httpRequest.status==200){
  //alert("성공");
  // alert(httpRequest.responseText);
   var xmlDoc=httpRequest.responseXML
   var bookList =xmlDoc.getElementsByTagName("book");
   var message =" 책 개수 :"+bookList.length+"권\n";
   for (var i=0;i<bookList.length ;i++ ){
   var book =bookList.item(i);
   var titleValue = book.getElementsByTagName("title").item(0).firstChild.nodeValue;
   var authorValue =book.getElementsByTagName("author").item(0).firstChild.nodeValue;
    message +=titleValue +"("+authorValue+")\n";

   }
   alert(message);
  }else{
   alert(httpRequest.status);
   alert("실패");
  }
 }
}


//-->
</SCRIPT>
<form name="testfrm" >
<input type="text" name="key" onkeyup="load('./test.xml')">
</form>

 

XML페이지(test.xml)

<?xml version="1.0" encoding="euc-kr"?>
<books>
 <book>
  <title>프로젝트 생존 전략</title>
  <author>스티브 맥코넬</author>
 </book>
 <book>
  <title>2.0 프로그래밍</title>
  <author>최범균</author>
 </book>
 <book>
  <title>웹표준</title>
  <author>네이버</author>
 </book>
</books>


출처 : http://blog.naver.com/dbrtp/60064501891