본문 바로가기

ETC

XML 노드 속성값 검색하기


Javascript Source

function getXMLDocument() {
 var xDoc = null;
         
// 파이어폭스
 if (document.implementation && document.implementation.createDocument) {
  xDoc = document.implementation.createDocument("","",null);
// 익스플로러
} else if (typeof ActiveXObject != "undefined") {
  var msXmlAx = null;
  try {
   //최신버젼
   msXmlAx = new ActiveXObject("Msxml2.DOMDocument");
  }
  catch (e) {
   //구 버젼
   msXmlAx = new ActiveXObject("Msxml.DOMDocument");
  }
  xDoc = msXmlAx;
 }
 return xDoc;
}
function xDocHandler () {
 var xDocPath = 'test.xml';
 this.objXdoc;
 this.xDoc = getXMLDocument
 this.objXdoc = this.xDoc();

 this.objXdoc.async = false;
 this.objXdoc.load(xDocPath);
}
function xDocNodeSearch(str) {
 var xDoc = new xDocHandler();
 var XmlDoc = xDoc.objXdoc.getElementsByTagName('item');
 var cnt = XmlDoc.length;
 for (var i = 0; i < cnt; i++) {
  if (XmlDoc[i].getAttribute('name') == str) {
   var alts = '[메세지] ' + xDoc.objXdoc.getElementsByTagName('msg')[i].firstChild.data;
   alts += '\n\n[링크]' + xDoc.objXdoc.getElementsByTagName('link')[i].firstChild.data;
   alert(alts);
  }
 }
}
xDocNodeSearch('test');
 
XML Source : test.xml
<?xml version="1.0" encoding="euc-kr" ?>
<message>
 <item name="test">
  <msg>안녕하세요. Syaku 블로그 입니다.</msg>
  <link>http://blog.naver.com/syaku</link>
 </item>
 <item name="test2">
  <msg>안녕하세요. 샤쿠 블로그 입니다.</msg>
  <link>http://blog.naver.com/syaku</link>
 </item>
</message>
 
출처 : http://syaku.tistory.com/trackback/13