본문 바로가기
front-end

[XML] XML 개념과 동기/비동기방식, HTTP 요청

by CodeMango 2023. 2. 1.

< XML 완벽 정리 > 

https://appmaster.io/ko/blog/xmliran-mueosibnigga

 

XML이란 무엇입니까? | AppMaster

XML(Extensible Markup Language) 관련 표준 및 기술에 대한 고품질 정보를 찾으십시오. 그것들을 사용하여 실제 문제를 해결하는 방법.

appmaster.io

XML(Extensible Markup Language)이라는 마크업 언어는 기계 및 사람이 읽을 수 있는 방식으로 텍스트 서식을 지정하기 위한 일련의 지침을 설정합니다. XML은 데이터를 저장하는 데 널리 사용되는 형식이며 인터넷에서 정보를 교환하는 데 널리 사용됩니다.

 

XML(Extensible Markup Language)은 표준 정보 형식을 형성하고 인터넷, 인트라넷 및 다른 곳에서 형식과 정보를 공유하는 유연한 방법입니다. 예를 들어, 컴퓨터 제조업체는 종종 컴퓨터 부품에 XML로 태그를 지정하여 제품을 보다 쉽게 식별하고 인벤토리를 작성할 수 있도록 합니다. 그런 다음 고객 서비스 담당자가 부품을 찾아야 할 때 XML 기반 부품 데이터베이스 를 검색할 수 있습니다.

 

개념정리

extensible markup language : 확장 표시 언어

- 파일, 데이터

- 파일 입출력

- 파일을 정교화 시켜둔 것

- 웹상에 올려놓는다.

- 태그로 관리하여 접근할 수 있게 한다. (사용자지정 태그)

- 태그값은 키값이라고도 한다.

- xml 다음 json 다음 csv가 나왔다.

 

목적

- 공공의 data를 공유하기 위한 목적

- setup 을 실행해주기 위한 목적. - 상수값 final int NUMBER = 100

 

사용처

- 서울열린데이터광장 사이트에서 확인할 수 있다.

https://data.seoul.go.kr/dataList/OA-12764/F/1/datasetView.do   : 서울열린데이터광장

 

열린데이터광장 메인

데이터분류,데이터검색,데이터활용

data.seoul.go.kr

https://wepplication.github.io/tools/beautifyCode/  : html정렬 사이트 

 

웹 소스코드 정렬 사이트

온라인 코드 정렬 사이트 js, css 등의 소스를 깔끔하게 정렬해주는 사이트

wepplication.github.io

 

xml 사용 예시 : 교통정보, 버스노선 등.. 

홍길동-24-서울시-2001/03/12

이 있을 때 홍길동이 뭔지 24가 뭘 뜻하는지 모를 수 있음

따라서 이것들을 태그로 관리하여 접근할 수 있게 할 수 있다.

 

예)

홍길동-24-서울시-2001/03/12

students 노드 : 2개
student 노드 : 4개

<students>  				// root tag
	<student>  				// node
		<name> 홍길동</name> 			// node
		<age> 24 </age>				   // node
		<address> 서울시 </address>	// node
		<birth> 2001/03/12 </birth>	   // node
	</student>				
	
	<students> 				// root tag
	<student> 				// node
		<name> 성춘향 </name>				// node
		<age> 16 </age>					// node
		<address> 남원시 </address>		// node
		<birth> 20011/05/18 </birth>	// node
	</student>

 

status와 readyState의 요소

      status
      200 : success
      403 : 접근금지
      404  : 없음 / 못찾겠음
      500 : 구문에러 / 문법이 틀렸음
      
      readyState
      0 : open 함수를 수행하기 전 상태
      1 : loading 중...
      2 : loading 완료
      3 : server 처리중
      4 : 처리완료
      
        --> 정상적 처리완료시 status : 200 , readyState : 4 나와야한다.

사용방법

	if(this.readyState == 4 && this.status == 200){
		xmlProc();  // 함수실행

 

XML 언어 뜯어보기

https://velog.io/@johnque/XMLHttpRequest-%EA%B0%9D%EC%B2%B4

 

XMLHttpRequest 객체

모든 모던한(최신의) 브라우저는 XMLHttpRequest 객체를 지원합니다.지금부터는 XMLHttpRequest => XHR로 부르겠습니다. 너무 기네요.XHR 객체는 전 편에도 말씀드렸듯이, 웹 서버와 데이터 교환을 백그라

velog.io

XMLHttpRequest => XHR

-  웹 서버와 데이터 교환을 백그라운드에서 비동기적으로 가능하게 해준다.

- 비동기적으로 데이터를 주고받음과 동시에 데이터가 도착했을 때, 리로드 하지 않고도 페이지의 일부 파트를 수정할 수 있게 해준다.

 

onreadystatechange

- readyState 속성값에 변화가 있으면, 불러야할 함수를 정의하는 부분이다.

- onreadystatechange가 실행됐을 때 function() 을 실행해라

 

open : Request를 구현한다.

 

responseText (responseText 프로퍼티)

- 서버에 요청하여 응답으로 받은 데이터를 문자열로 반환한다.

- 데이터가 넘어왔는지 확인할 때도 쓰인다.

   ex) console.log(this.responseText);

 

DOM (Document Object Model)

https://blog.naver.com/scyan2011/221619739975

 

자바스크립트/DOM1/정의

DOM(Document Object Model) 앗! 조금 생소한 용어가 나온다고 걱정하지 마세요. DOM이란 W3C (...

blog.naver.com

- 문서의 각 요소에 접근하고 다루는 표준화된 방법

 

 

DomPaser

- string형태의 XML  또는 HTML을 DOm 구조로 변경하기- 문자열(string)의 XML 또는 HTML 소스 코드를 DOM Document로 분석∙구조화(parse) 할 수 있는 기반을 제공한다.생성코드

let domParser = new DOMParser()

 

parseFromString() : DomPaser 인터페이스의 메서드

parseFromString(string, mimeType)

string 자리

구문 분석할 문자열. HTML , xml , xhtml+xml 또는 svg 문서 를 포함해야 한다.

 

mimeType 자리

문자열. 이 문자열은 XML 파서 또는 HTML 파서를 사용하여 문자열을 구문 분석하는지 여부를 결정합니다. 유효한 값은 다음과 같다.

  • text/html
  • text/xml
  • application/xml
  • application/xhtml+xml
  • image/svg+xml

text/html 값은 HTML 파서를 호출하고 메서드는 HTMLDocument 를 반환한다 .

다른 유효한 값( text/xml , application/xml , application/xhtml+xml 및 image/svg+xml )은 기능적으로 동일하다. 이들은 모두 XML 파서를 호출하고 메서드는 XMLDocument 를 반환한다.

 

예제)

	let parser, xmlDoc;

	parser = new DOMParser();
	xmlDoc = parser.parseFromString(xmltext, "text/html");

동기 vs 비동기

https://backendcode.tistory.com/92

 

[Ajax] 란? - 동기/비동기, XMLHttpRequest

2022.03.15(56일 차_화요일) 오늘부터 약 3일간 ajax에 대해 배운다! 이번 글에는 Ajax 정의에 대해 정리하고, 다음 글에서 jQuery와 함께 실습 예제를 정리할 예정이다. Ajax란? Asynchronous Javascript And XML (비

backendcode.tistory.com

동기(Synnchronous) : false

  • 작업이 여러 개일 경우 일을 순차적으로 진행하는 것
  • 클라이언트가 서버한테 데이터를 요구할 때 서버에서 데이터를 보낼 때까지 가만히 기다리는 상황
  • ex) 커피를 주문할 때 뒷사람은 앞사람이 커피를 주문하고 받을 때까지 기다려야 함

비동기(Asynchronous) : true

  • 작업이 여러 개 일 경우 일을 순차적으로 진행하지 않는 것
  • 클라이언트가 서버한테 데이터를 요구할 때 서버의 응답을 기다리지 않고도 다른 일을 수행함
  •  ex) 커피를 주문한 사람을 진동벨을 받고 기다리고, 다음 사람은 계속 커피 주문이 가능하다. (능률적)

request / response

Client가 request '요청' 하고 Server가 response '응답'함

이걸 순서대로 하는게 동기/ 순서대로 하지 않는게 비동기


노드로의 접근

http://www.tcpschool.com/javascript/js_dom_nodeAccess

 

코딩교육 티씨피스쿨

4차산업혁명, 코딩교육, 소프트웨어교육, 코딩기초, SW코딩, 기초코딩부터 자바 파이썬 등

tcpschool.com

 

노드간의 관계를 이용하여 접근하는 방법

HTML DOM에서 노드 간의 관계는 다음과 같은 프로퍼티로 정의됩니다.

 

1. parentNode : 부모 노드

2. childNodes : 자식 노드 리스트

3. firstChild : 첫 번째 자식 노드

4. lastChild : 마지막 자식 노드

5. nextSibling : 다음 형제 노드

6. previousSibling : 이전 형제 노드

 

위와 같은 프로퍼티를 이용하여 원하는 노드에 손쉽게 접근할 수 있습니다.


사용방법

 

1. HTTP 요청 방법

1. XMLHttpRequest()를 통해 오브젝트 생성을 한다.

2. function을 실행한다.

3. open() 함수를 통해 메소드 방식, url, 그리고 비동기 여부를 설정한다.

4. send(data) 로 설정한 방식대로 request를 보낸다.(data는 null이어도 된다.)

 

2. 형변환 (문자열 -> xml)

// - xml이 문자로 되어있으면 parser을 통해 형변환 필요함
// - xmlDoc : xmlDocument의 약자

// alert(xmltext); // (변경 전) : 문자열 string(위의 날 것 그대로의 문자열)

	let parser, xmlDoc;		

	parser = new DOMParser();
	xmlDoc = parser.parseFromString(xmltext, "text/html");  // HTMLDocument 반환됨(블로그설명 참조)
	
// DOMParser를 통해 파싱을 한 후 string이 xml데이터로 바뀐다.
// alert(xmlDoc);  // (변경 후) : xml(object) :

3. 접근(난이도 상)

document.getElementById("demo").innerHTML 
1번 = xmlDoc.getElementsByTagName("book")[1].childNodes[0].nodeName; // title
2번 = xmlDoc.getElementsByTagName("book")[1].childNodes[0].childNodes[0].nodeValue; // 이솝이야기
3번 = xmlDoc.getElementByTagName("book").length; // 2
4번 = xmlDoc.getElementByTagName("book")[1].childNodes.length; //3

1번. nodeName (tag) 을 가져오기

= xmlDoc.getElementsByTagName("book")[1].childNodes[0].nodeName;

# getElementsByTagName :

- 특정 태그명을 가지고 있는element 의 집합 

- 태그 이름을 지정해 취득한 반환값은 HTMLCollection 오브젝트 형태로 반환된다. (배열로 넘어온다)

- 아래 문제에서는 배열로 넘어오지 않았지만, 객체째로 있을때 배열로 넘어옴 (아래 work 과제에서 확인)

 

문장을 반으로 쪼개서 분석한다.

 xmlDoc.getElementsByTagName("book")[1]                             .childNodes[0].nodeName; 

 

 xmlDoc.getElementByTagName("book")[1]   : TagName이 "book" 인 xmlDocument(객체)의 1번지 반환  

반환값
   				"<book>" + 	
					"<title> 이솝이야기</title>" + 
					"<author> woman </author>" + 
					"<year> 2004 </year>" + 	
				"</book>" +

 .childNodes[1].nodeName;  : book 객체 1번지의 childNodes 중에 0번지의 nodeName 반환

반환값 : title  (nodeName이므로)

 

2번. 값을 가져오기

= xmlDoc.getElementsByTagName("book")[1].childNodes[0].childNodes[0].nodeValue;

 

= xmlDoc.getElementsByTagName("book")[1].childNodes[0].까지는 위와 동일하다.

childNodes[0]은  "<title> 이솝이야기</title>"  를 말하고 이 문장의 node는 이솝이야기이다.

이 문장의 node는 단 하나고 그것이 이솝이야기이고 당연히 0번지가 된다.

--> 

 xmlDoc.getElementsByTagName("book")[1].childNodes[0].childNodes[0]. 가 이솝이야기이고

그 이솝이야기의 값을 가져오려면 nodeValue를 써야한다.

-->  xmlDoc.getElementsByTagName("book")[1].childNodes[0].childNodes[0].nodeValue;   

의 반환값은 "이솝이야기"가 된다. 

반환값 : 이솝이야기

 

3번. 데이터의 길이 가져오기

= xmlDoc.getElementByTagName("book").length;

book 객체 배열의 길이값 = 배열에 몇개가 들었나 ? : book 객체 2개

반환값 : 2

 

4번. 컬럼의 갯수 가져오기

= xmlDoc.getElementByTagName("book")[1].childNodes.length; 

book 객체 1번지의 childNodes 개수는 3개

반환값 : 3

 

 


 

연습문제1 . txt 파일의 데이터를 읽어오기 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<p id="demo"></p>

<button type="button" onclick="loadTextDoc()"> 내용보기 </button>


<script type="text/javascript">
function loadTextDoc(){
// Ajax
//1. xhttp의 객체 생성
	let xhttp = new XMLHttpRequest();  //XMLHttpRequest:파일을 서버에서 읽어온다
	
//2. function 실행
// onreadystatechange 객체 xhttp 안에 있는 onreadystatechange가 동작을 하게 되면 function실행
 	xhttp.onreadystatechange = function(){	
/* 		console.log(this.responseText) 		//this :위 문장의 xhttp /responseText:응답한 텍스트 |출력 : 읽어온 데이터
		console.log(this.status);			//status :상태 알 수 있는것  |출력 : 200
		console.log(this.readyState);		//readyState : 준비된 상태인지 알아보기 |출력: 0,1,2,3,4  */
	
		if(this.readyState == 4 && this.status == 200){
			document.getElementById("demo").innerHTML = this.responseText;
										//responseText :  서버에 요청하여 응답으로 받은 데이터를 문자열로 반환한다.
		} 
	}	
// 3. open : 메소드방식, 비동기 여부 설정
//	xhttp.open(method, url, async);		// sync : 동기화 / async : 비동기 구글링해보기
	xhttp.open("GET", "test.txt", true);	//false :동기화 /true : 비동기
	console.log("xhttp.open");

// 4. send : request를 보냄.
	xhttp.send();
	console.log("xhttp.send()");
}

</script>

</body>
</html>

 

 연습문제2 . 형변환과 접근 방법

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<p id="demo">3</p>

<script type="text/javascript">

// root :books / books의 노드 : book (2개) / book의 노드 : title, author, year (3개)


let xmltext = "<books>" + 		// root tag
				"<book>" + 	// ("book")[0] - books의 node
					"<title> 탈무드</title>" +    //childNodes[0]
					"<author> man </author>" +  //childNodes[1]
					"<year> 2001 </year>" + 	//childNodes[2]
				"</book>" +
			   
				"<book>" + 	// ("book")[1] - books의 node
					"<title> 이솝이야기</title>" +  // childNodes[0]
					"<author> woman </author>" + // childNodes[1]
					"<year> 2004 </year>" + 	 //childNodes[2]
				"</book>" +
			  "</books>";
			  
			  
// 1. 형변환 (문자열 -> xml)
// xml이 문자로 되어있으면 parser을 통해 형변환 필요함
// xmlDoc : xmlDocument의 약자
// alert(xmltext); // (변경 전) : 문자열 string(위의 날 것 그대로의 문자열)

	let parser, xmlDoc;

	parser = new DOMParser();
	xmlDoc = parser.parseFromString(xmltext, "text/html");  // HTMLDocument 반환됨(블로그설명 참조)
	
// DOMParser를 통해 파싱을 한 후 string이 xml데이터로 바뀐다.
// alert(xmlDoc);  // (변경 후) : xml(object) : 

// 2. 접근
		
	document.getElementById("demo").innerHTML 
//	= xmlDoc.getElementsByTagName("book")[1].childNodes[0].nodeName; // title
//	= xmlDoc.getElementsByTagName("book")[1].childNodes[1].nodeName; // author

//	= xmlDoc.getElementsByTagName("book")[1].childNodes[0].childNodes[0].nodeValue; // 이솝이야기
//	= xmlDoc.getElementsByTagName("book").length; // 데이터의 길이
	= xmlDoc.getElementsByTagName("book")[1].childNodes.length; // 컬럼의 갯수
</script>


</body></html>

 

 연습문제3-1 . nodeValue 가져오기

<p id = "demo"></p>

<script type="text/javascript">

//1. xhttp의 객체 생성
let xhttp = new XMLHttpRequest();

//2. function 생성
// onreadystatechange 객체 xhttp 안에 있는 onreadystatechange가 동작을 하게 되면 function실행
xhttp.onreadystatechange =function(){

	
		if(this.readyState == 4 && this.status == 200){
//			nodeValFunc(this); // this = xhttp
//			nodeNameFunc(xhttp); // this라고 해도되고 xhttp 직접 써도된다.
			childNodeFunc(xhttp);
		}
}
// xhttp.open(method, url, async)
xhttp.open("GET", "client.xml", true);  // 비동기 : true
xhttp.send();

// 여기서 작업하기 위해 위의 xhttp 를 넘긴다.


// <1교시> nodeValue 가져오기
function nodeValFunc(xhttp){
	let num, name; // num =client파일의 번호 / name = cline 파일의 주소
	let txt, nametxt, xmlDoc; // xomDoc: xmldocument
	

// 문자열 초기화
	txt = nametxt = "";
	/* 	txt = "";
	numtxt = "";  둘다 같은 값이니까 줄여서 쓸 수 있다. */ 
	
// xml 데이터 넘어오게 하는 방법
	xmlDoc = xhttp.responseXML;  //xmldocument = 매개변수.responseXML;
	console.log(xmlDoc);
	
// 태그네임 "번호"인 xmldocument의 배열을 num에 넣는다.
 	num = xmlDoc.getElementsByTagName("번호");  // <번호> 1 </번호> ,<번호> 2 </번호>,<번호> 3 </번호>
// 태그네임 "이름"인 xmldocument의 배열을 name에 넣는다.
	name = xmlDoc.getElementsByTagName("이름"); // <이름>홍길동</이름>,<이름>성춘향</이름>,<이름>일지매</이름>
	console.log(num.length); // 3 반환 (1,2,3으로 세개니까) num과 name길이 똑같음.


//	let datas = ""; // 방법2)의 변수 datas
	
	for( i=0; i<num.length; i++){
	// num : "번호"들/ childNodes :3개 / nodeValue = 1,2,3
	
// 방법(1) 번호 나오고나서 이름 나오게 하는법
		txt = txt + num[i].childNodes[0].nodeValue + "<br>"; 		// 1,2,3
	//num1일때 값 : <번호> 1 </번호> -> childNodes는 딱 한개 -> childNodes[0]으로 고정
		nametxt += name[i].childNodes[0].nodeValue + "<br>";	// 홍길동, 성춘향, 일지매
	
// 방법(2) 번호 바로 옆에 이름 나오게 하는법
//		datas += num[i].childNodes[0].nodeValue + " "; 		// 1,2,3
//		datas += name[i].childNodes[0].nodeValue + "<br>";
	}
	document.getElementById("demo").innerHTML = txt + nametxt;	// 방법(1)
}
/* 방법(1) 출력값
	1
	2
	3
	홍길동
	성춘향
	일지매 	*/
//	document.getElementById("demo").innerHTML = datas;			// 방법(2)
/* 방법(2) 출력값 
	1 홍길동
	2 성춘향
	3 일지매 	*/

 연습문제3-2 . tag명 가져오기

<p id = "demo"></p>

<script type="text/javascript">

//1. xhttp의 객체 생성
let xhttp = new XMLHttpRequest();

//2. function 생성
// onreadystatechange 객체 xhttp 안에 있는 onreadystatechange가 동작을 하게 되면 function실행
xhttp.onreadystatechange =function(){

	
		if(this.readyState == 4 && this.status == 200){
//			nodeValFunc(this); // this = xhttp
//			nodeNameFunc(xhttp); // this라고 해도되고 xhttp 직접 써도된다.
			childNodeFunc(xhttp);
		}
}
// xhttp.open(method, url, async)
xhttp.open("GET", "client.xml", true);  // 비동기 : true
xhttp.send();

// <2교시> - tag명 가져오기
//  xml의 데이터를 보면 태그명이 다 다르다. 

	function nodeNameFunc(xhttp){
	
//root tag부터 살펴보자
	let arr, txt;
	let xmlDoc;
	
	 txt = ""; //텍스트엔 빈문자열 준비해놓기
	 
// xml 데이터 넘어오게 하는 방법	 
	 xmlDoc = xhttp.responseXML;
	 
//우선 childNode가 뭔지 알아야한다. 
// root tag에 있는 childNodes : <고객> 3개
	arr = xmlDoc.documentElement.childNodes; //childNode 를 arr에 넣음
// arr 에 고객 3개 들어있음 0번지, 1번지, 2번지

//nodeName은 root도 포함되므로
// <고객들> <고객> </고객> <고객> </고객> <고객> </고객> 7개가 txt에 들어가게됨
// 서버 출력시에는 #text 고객 #text 고객 #text 고객 #text로 반환됨 / #text : 데이터가 없는것
// 따라서 조건문으로 nodeType==1 (데이터가 있는것) 만 반환하게 해준다.
	for(i = 0; i<arr.length; i++ ){
		if(arr[i].nodeType == 1){
		txt = txt + arr[i].nodeName + "<br>";  // nodeName들을 모아준다.
		}
	}
	document.getElementById("demo").innerHTML = txt;
// 조건문을 통해 서버 출력시    고객 고객 고객    반환된다.

}
// <고객> 안의 node들 얻어오는 방법
	function childNodeFunc(xhttp) {
		let arr, txt;
		let xmlDoc;
		
		txt = "";
		
		xmlDoc = xhttp.responseXML;
		
		arr = xmlDoc.getElementsByTagName("고객")[0];

// 길이값 보기 
	// len = 고객 데이터 안에 있는 childNodes의 길이 =9 
		let len = arr.childNodes.length;
		console.log(len);		//9
// ㄴ 4가 나올줄 알았는데 왜 9가 나옴? 
// <고객> <번호> </번호> <이름> </이름> <주소> </주소> <방문> </방문> 총 9개 나온것.

// firstChild: 첫번째 자식노드
	//맨 첫번째 node로 보내기 위해서 첫번째 node를 잡아놓는다.
	let fchild = arr.firstChild; // 
//		console.log(fchild)		// #text 반환
		
 	for(i = 0; i<len; i++){ //9만큼 돌아감
		if(fchild.nodeType == 1){  // nodeType == 1 -> 데이터 있을 때만 출력
		txt = txt + i + " " + fchild.nodeName + "<br>";
		// 0  <고객>
		}
		fchild = fchild.nextSibling;	// 다음 형제 노드
	}
		document.getElementById("demo").innerHTML = txt;
        
   /*  조건문 없을때 출력값
	0 #text
	1 번호
	2 #text
	3 이름
	4 #text
	5 주소
	6 #text
	7 방문
	8 #text 
	
	조건문 있을때 출력값
	1 번호
	3 이름
	5 주소
	7 방문  */

 

연습문제 3-1 + 3-2 합친버전 (코드 저장용)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p id = "demo"></p>

<script type="text/javascript">

//1. xhttp의 객체 생성
let xhttp = new XMLHttpRequest();

//2. function 생성
// onreadystatechange 객체 xhttp 안에 있는 onreadystatechange가 동작을 하게 되면 function실행
xhttp.onreadystatechange =function(){

	
		if(this.readyState == 4 && this.status == 200){
//			nodeValFunc(this); // this = xhttp
//			nodeNameFunc(xhttp); // this라고 해도되고 xhttp 직접 써도된다.
			childNodeFunc(xhttp);
		}
}
// xhttp.open(method, url, async)
xhttp.open("GET", "client.xml", true);  // 비동기 : true
xhttp.send();

// 여기서 작업하기 위해 위의 xhttp 를 넘긴다.


// <1교시> nodeValue 가져오기
function nodeValFunc(xhttp){
	let num, name; // num =client파일의 번호 / name = cline 파일의 주소
	let txt, nametxt, xmlDoc; // xomDoc: xmldocument
	

// 문자열 초기화
	txt = nametxt = "";
	/* 	txt = "";
	numtxt = "";  둘다 같은 값이니까 줄여서 쓸 수 있다. */ 
	
// xml 데이터 넘어오게 하는 방법
	xmlDoc = xhttp.responseXML;  //xmldocument = 매개변수.responseXML;
	console.log(xmlDoc);
	
// 태그네임 "번호"인 xmldocument의 배열을 num에 넣는다.
 	num = xmlDoc.getElementsByTagName("번호");  // <번호> 1 </번호> ,<번호> 2 </번호>,<번호> 3 </번호>
// 태그네임 "이름"인 xmldocument의 배열을 name에 넣는다.
	name = xmlDoc.getElementsByTagName("이름"); // <이름>홍길동</이름>,<이름>성춘향</이름>,<이름>일지매</이름>
	console.log(num.length); // 3 반환 (1,2,3으로 세개니까) num과 name길이 똑같음.


//	let datas = ""; // 방법2)의 변수 datas
	
	for( i=0; i<num.length; i++){
	// num : "번호"들/ childNodes :3개 / nodeValue = 1,2,3
	
// 방법(1) 번호 나오고나서 이름 나오게 하는법
		txt = txt + num[i].childNodes[0].nodeValue + "<br>"; 		// 1,2,3
	//num1일때 값 : <번호> 1 </번호> -> childNodes는 딱 한개 -> childNodes[0]으로 고정
		nametxt += name[i].childNodes[0].nodeValue + "<br>";	// 홍길동, 성춘향, 일지매
	
// 방법(2) 번호 바로 옆에 이름 나오게 하는법
//		datas += num[i].childNodes[0].nodeValue + " "; 		// 1,2,3
//		datas += name[i].childNodes[0].nodeValue + "<br>";
	}
	document.getElementById("demo").innerHTML = txt + nametxt;	// 방법(1)
}
/* 방법(1) 출력값
	1
	2
	3
	홍길동
	성춘향
	일지매 	*/
//	document.getElementById("demo").innerHTML = datas;			// 방법(2)
/* 방법(2) 출력값 
	1 홍길동
	2 성춘향
	3 일지매 	*/

	
	
// <2교시> - tag명 가져오기
//  xml의 데이터를 보면 태그명이 다 다르다. 

	function nodeNameFunc(xhttp){
	
//root tag부터 살펴보자
	let arr, txt;
	let xmlDoc;
	
	 txt = ""; //텍스트엔 빈문자열 준비해놓기
	 
// xml 데이터 넘어오게 하는 방법	 
	 xmlDoc = xhttp.responseXML;
	 
//우선 childNode가 뭔지 알아야한다. 
// root tag에 있는 childNodes : <고객> 3개
	arr = xmlDoc.documentElement.childNodes; //childNode 를 arr에 넣음
// arr 에 고객 3개 들어있음 0번지, 1번지, 2번지

//nodeName은 root도 포함되므로
// <고객들> <고객> </고객> <고객> </고객> <고객> </고객> 7개가 txt에 들어가게됨
// 서버 출력시에는 #text 고객 #text 고객 #text 고객 #text로 반환됨 / #text : 데이터가 없는것
// 따라서 조건문으로 nodeType==1 (데이터가 있는것) 만 반환하게 해준다.
	for(i = 0; i<arr.length; i++ ){
		if(arr[i].nodeType == 1){
		txt = txt + arr[i].nodeName + "<br>";  // nodeName들을 모아준다.
		}
	}
	document.getElementById("demo").innerHTML = txt;
// 조건문을 통해 서버 출력시    고객 고객 고객    반환된다.

}
// <고객> 안의 node들 얻어오는 방법
	function childNodeFunc(xhttp) {
		let arr, txt;
		let xmlDoc;
		
		txt = "";
		
		xmlDoc = xhttp.responseXML;
		
		arr = xmlDoc.getElementsByTagName("고객")[0];

// 길이값 보기 
	// len = 고객 데이터 안에 있는 childNodes의 길이 =9 
		let len = arr.childNodes.length;
		console.log(len);		//9
// ㄴ 4가 나올줄 알았는데 왜 9가 나옴? 
// <고객> <번호> </번호> <이름> </이름> <주소> </주소> <방문> </방문> 총 9개 나온것.

// firstChild: 첫번째 자식노드
	//맨 첫번째 node로 보내기 위해서 첫번째 node를 잡아놓는다.
	let fchild = arr.firstChild; // 
//		console.log(fchild)		// #text 반환
		
 	for(i = 0; i<len; i++){ //9만큼 돌아감
		if(fchild.nodeType == 1){  // nodeType == 1 -> 데이터 있을 때만 출력
		txt = txt + i + " " + fchild.nodeName + "<br>";
		// 0  <고객>
		}
		fchild = fchild.nextSibling;	// 다음 형제 노드
	}
		document.getElementById("demo").innerHTML = txt; 
}	
	
/*  조건문 없을때 출력값
	0 #text
	1 번호
	2 #text
	3 이름
	4 #text
	5 주소
	6 #text
	7 방문
	8 #text 
	
	조건문 있을때 출력값
	1 번호
	3 이름
	5 주소
	7 방문  */
	
</script>
</body>
</html>

 

xml 과제 : xml 데이터 이용해서 테이블 만들기

<과제의 xml파일 데이터>

<?xml version="1.0" encoding="UTF-8"?>

<books>
	<book>
		<title> 원씽 </title>
		<author>게리켈러 </author>
		<date> 2013/08/30 </date>
		<price> 12,000 </price>
	</book>

	<book>
		<title> 트렌드코리아2023 </title>
		<author> 김난도 </author>
		<date> 2022/10/05 </date>
		<price> 17,000 </price>
	</book>

	<book>
		<title> 불편한편의점 </title>
		<author> 김호연 </author>
		<date> 2021/04/20 </date>
		<price> 12,000 </price>
	</book>

	<book>
		<title> 역행자 </title>
		<author> 웅진 </author>
		<date> 2022/06/03 </date>
		<price> 15,000 </price>
	</book>

	<book>
		<title> 하얼빈 </title>
		<author> 김훈 </author>
		<date>2022/08/03 </date>
		<price> 14,000 </price>
	</book>

</books>

과제 방법1. 문자열로 테이블 만들기

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
과제 방법1. 문자열로 테이블 만들기

<div id="demo">
</div>

<script type="text/javascript">

//1. xhttp의 객체 생성
let xhttp = new XMLHttpRequest();

//2. function 생성
// onreadystatechange 객체 xhttp 안에 있는 onreadystatechange가 동작을 하게 되면 function실행
xhttp.onreadystatechange = function () {
	if(this.readyState == 4 && this.status == 200){
		xmlProc( xhttp );
	}	
}
//3. open : 메소드방식, 비동기 여부 설정
xhttp.open("GET", "books.xml", true);

//4. send : request를 보냄.
xhttp.send();

// 괄호에는 가인수를 적는 거고 위와 같은 이름 안 적는게 좋으므로 xml로 적었음
function xmlProc( xml ) {


// xml 데이터 넘어오게 하는 방법
	let xmlDoc = xml.responseXML;
	// alert(xmlDoc); //object XMLDocument 반환
	
// root명 취득 : books
	let rootTagName = xmlDoc.documentElement.nodeName;
	// alert(rootTagName); //books 반환
	
// node명 취득 : root books의 node는 book 
	let nodeArr = xmlDoc.documentElement.childNodes;
	//alert(nodeArr);  //object NodeList 반환 (11개 포함)
	
/* 콘솔값 (nodeArr 의 값) 
<books> 
<book></book> 
<book> </book>
<book> </book>
<book> </book>
<book> </book> 에서 if문으로 걸러내면 <book> 5개가나옴 */

// node list 확인
	let nodeName;
	for(i = 0;i < nodeArr.length; i++){ 
		if(nodeArr[i].nodeType == 1){	// nodeType==1은 데이터가 있다는 말
			nodeName = nodeArr[i].nodeName;
//			console.log(nodeName);
		
/* 콘솔값 (nodeName 의 값)
<book>
<book>
<book>
<book>
<book>
이 들어있다 */
		}
	} 
	
// 1. table을 준비
	let table = "<table border='1'>";
	table += "<col width='50'><col width='100'><col width='140'><col width='100'><col width='140'>";
	table += "<tr>"; // tr열어주기
	table += "<th>번호</th>";
	
 //	2. getElementsByTagName 을 사용해 첫번째 book의 객체 가져오기

/* 	 getElementsByTagName 이란? 
	특정 태그명을 가지고 있는element 의 집합
	태그 이름을 지정해 취득한 반환값은 HTMLCollection 오브젝트 형태로 반환된다. 
	--> nodeName에는 <book> 5개가 담겨있음. 그것의 0번지도 어차피 <book>
	<book>의 객체 그 자체를 담는다. 
*/
	columnName = xmlDoc.getElementsByTagName(nodeName)[0];
	
/* 콘솔값 (columnName의 값)
	<book>
		<title> 원씽 </title>
		<author>게리켈러 </author>
		<date> 2013/08/30 </date>
		<price> 12,000 </price>
	</book> 
*/

// 3. 컬럼값 가져오기 (th에 넣기)
	let child = columnName.firstChild;  // #text (first니까 데이터가 없음)
//	console.log(child); // #text
//	console.log(columnName.childNodes.length); // 9개 반환 : </book> 빼고 다 반환
	
	for(i = 0;i < columnName.childNodes.length; i++){ //9번 반복
		if(child.nodeType == 1){ // 데이터가 있다면
			table += "<th>" + child.nodeName + "</th>";	 //nodeName은 tag 값이다.
//			console.log(child.nodeName); 
		}		
		child = child.nextSibling; // child는 계속 갱신됨
}//for문 끝		
	
	//tr 닫아주기
	table += "</tr>";
	
// 4. data 출력

// 4-1. 먼저 nodeName의 길이값을 구한다. : 5
	let len = xmlDoc.getElementsByTagName(nodeName).length; 
	console.log(len); // 5 반환
	
/* 콘솔값 (nodeName 의 값) : 5개
	<book>
	<book>
	<book>
	<book>
	<book> */
	
// 4-2. 길이값을 이용해 반복문을 만든다.	
	for(i = 0;i < len; i++){ //5번 반복
	
// 4-3. 테이블에 데이터 넣기 위해 tr, th를 준비한다.
		table += "<tr>"; // tr 열기
		table += "<th>" + (1 + i) + "</th>"; // "번호"열 뿌리기

// 4-4. 데이터값 가져온다. (td에 넣기)
		let dataArr = xmlDoc.getElementsByTagName(nodeName)[i];
		console.log(dataArr);
// dataArr = book[0]의 배열 ~ book[4]의 배열이 dataArr로 넘어옴

		child = dataArr.firstChild; 
	
/* 	콘솔값 (child 의 값)
<book>
<title> 원씽 </title>
<author>게리켈러 </author>
<date> 2013/08/30 </date>
<price> 12,000 </price>
</book>   */
		for(j = 0;j < dataArr.childNodes.length; j++){ // 9번반복
		
/* 콘솔값 (dataArr.childNodes의 값) : 9개
<book> 
<title></title><author></author><date></date><price></price>   */
		if(child.nodeType == 1){
			table += "<td>" + child.childNodes[0].nodeValue + "</td>";
		}	//childNodes[0] 각 키값의 value값일 수밖에 없음.(value 하나씩밖에 없으니까 0번지)
		child = child.nextSibling;
}// for문 끝
		
		table += "</tr>"; // tr 닫기
}
		table += "</table>" // table 닫기
	
	document.getElementById("demo").innerHTML = table;	
}

	
</script>

</body></html>

 

과제 방법2. createElement로 테이블 만들기 ( 분석 안함 / 주석 안 달았음)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<div id="demo">
<table border="1" id="table">
<col width='50'><col width='100'><col width='140'><col width='100'><col width='140'>

</table>
</div>

<script type="text/javascript">

let xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function () {
	if(this.readyState == 4 && this.status == 200){
		xmlProc( xhttp );
	}	
}
xhttp.open("GET", "books.xml", true);
xhttp.send();

function xmlProc( xml ) {
	
	let xmlDoc = xml.responseXML;
	// alert(xmlDoc);
	
	// root명 취득
	let rootTagName = xmlDoc.documentElement.nodeName;
	// alert(rootTagName);
	
	// node명 취득
	let nodeArr = xmlDoc.documentElement.childNodes;
	//alert(nodeArr);
	
	// node list 확인
	let nodeName;
	for(i = 0;i < nodeArr.length; i++){
		if(nodeArr[i].nodeType == 1){
			nodeName = nodeArr[i].nodeName;
			console.log(nodeName);
		}
	} 
	
	// table을 준비
	let table = document.getElementById("table");
	
	let tr = document.createElement("tr");
	
	th = document.createElement("th");
	th.appendChild( document.createTextNode("번호") );
		
	// column명(tag명)을 취득
	columnName = xmlDoc.getElementsByTagName(nodeName)[0];
	
	let child = columnName.firstChild;
	console.log(columnName.childNodes.length);
	tr.appendChild(th);	
	
	for(i = 0;i < columnName.childNodes.length; i++){
		if(child.nodeType == 1){									
			th = document.createElement("th");			
			th.appendChild( document.createTextNode(child.nodeName) );
			console.log(child.nodeName);
			
			tr.appendChild(th);
		}		
		child = child.nextSibling;
	}	
	table.appendChild(tr);
		
	// data 출력
	
	let len = xmlDoc.getElementsByTagName(nodeName).length;
	console.log(len);
	
	for(i = 0;i < len; i++){
	
		tr = document.createElement("tr");
		
		th = document.createElement("th");	
		th.appendChild( document.createTextNode(1 + i + "") );		
		tr.appendChild(th);
		
		let dataArr = xmlDoc.getElementsByTagName(nodeName)[i];
		
		child = dataArr.firstChild;
		for(j = 0;j < dataArr.childNodes.length; j++){
			if(child.nodeType == 1){				
				let td = document.createElement("td");
				td.appendChild( document.createTextNode(child.childNodes[0].nodeValue) );	
				tr.appendChild(td);
			}
			child = child.nextSibling;
		}		
		
		table.appendChild(tr);
	}		
}
</script>


</body>
</html>

 

댓글