본문 바로가기

WEB

[XML] XML이란?

XML ( eXtensible Markup Language )

  • 공유용 데이터를 배포할 경우 사용하는 파일
  • tag명을 한글 기입해도 된다.
  • setup용으로 사용
  • standard한 tag가 없다.

 

function loadXMLDoc() {
	let xhttp = new XMLHttpRequest(); // 웹을 통해 xml을 요청한다.(비동기)
	xhttp.onreadystatechange = function() {
		// 읽어오는 부분
			if (this.readyState == 4 && this.status == 200) { // success
			document.getElementById('demo').innerHTML = this.responseText;
		}
	}
	xhttp.open("GET", "test.txt", true);
	xhttp.send();
}


ReadyState

  • 0 : open() 메소드를 수행하기 전
  • 1 : loading중
  • 2 : loading완료
  • 3 : server 처리중
  • 4 : server 처리완료

 

Status

  • 200 : Success
  • 403 : 접근거부
  • 404 : not found 찾을 수 없음 (예 : 파일을 못 찾음)
  • 500 : syntax error 문법 에러

 

예제)

xml 파일

let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
	if (this.readyState == 4 && this.status == 200) {
		//nodeValueFunc(this);
		nodeNameFunc(this);
		//dataFunc(this);
	}
}
xhttp.open("GET", "movie.xml", true);
xhttp.send();

function nodeValueFunc(xml) {
	let arr, txt, xmlDoc;
	xmlDoc = xml.responseXML; // xml을 받아올때
	txt = "";
	arr = xmlDoc.getElementsByTagName("제목");
	for (i = 0; i < arr.length; i++) {
	txt += arr[i].childNodes[0].nodeValue + "<br>";
	}
	document.getElementById('demo').innerHTML = txt;
}

- nodeValue 대신 nodeName을 사용하면 태그명을 가져올 수 있다.

 

function dataFunc(xml) {
	let arr, txt, xmlDoc;
	xmlDoc = xml.responseXML;
	txt = "";

	arr = xmlDoc.getElementsByTagName("영화")[0];
	let xlen = arr.childNodes.length;

	y = arr.firstChild;

	for (var i = 0; i < xlen; i++) {
		if (y.nodeType == 1) {
			txt += " : " + y.nodeName + ":" + y.childNodes[0].nodeValue + "<br>";
		}
		y = y.nextSibling;
	}
	document.getElementById('demo').innerHTML = txt;
}

- nextSibling : 같은 노드 레벨의 다음 값을 가져온다.

'WEB' 카테고리의 다른 글

[JQuery] Jquery란?  (0) 2022.06.29
[JSON] JSON이란?  (0) 2022.06.28
[JS] 개념  (0) 2022.06.24
[CSS-01] 개념, Selector  (0) 2022.06.22
[HTML-03] Link, CheckBox, Radio, Form  (0) 2022.06.22