STUDY/jQuery & Ajax

Document Object Model과 XML

Anne of Green Galbes 2019. 4. 2. 12:41

Document Object Model과 XML



1. DOM객체

○ 문서를 객체로 표현하기 위한 표준

○ HTML이나 XML 등의 문서를 객체로 표현할 때 사용되는 API


① XML DOM트리 구조


② HTML DOM트리 구조

2. 주요 DOM API

○ 모든건 Node로 표현되며 문서의 각 구성 요소들은 모두 Node 또는 하위 인터페이스로 매핑된다

 - Document : 전체 문서

 - Element : 각 태그

 - Text : 문자열 데이터

 - CDataSection : XML문서의 CDATA영역의 문자열 값을 저장


○ Node 인터페이스의 주요 프로퍼티

프로퍼티 타입

프로퍼티 이름 

설명 

String

nodeName

 노드의 이름

String 

nodeValue

 노드의 값

unSigned short

nodeType

 노드 타입

Node

ParentNode

 부모 노드 

NodeList

childNodes

 자식 노드 목록

Node

firstChild

 첫 번째 자식 노드

Node

lastChild

 마지막 자식 노드

Node

previoucSibling

 현재 노드와 같은 부모를 갖는 자식 노드 중 현재 노드 이전의 자식 노드

Node

nextSibling

 현재 노드와 같은 부모를 갖는 자식 노드 중 현재 노드 다음의 자식 노드

 Document

ownerDocument

 이 노드가 포함된 Document 객체


예제 1 HTML DOM 객체


① changeHTMLUsingDOM.html

addItem

○ 문서에 HTML 엘리먼트 추가

- createElement() : 요소를 생성

var newItemE = document.createElement("div");

→ <div> </div>

- appendChild() : 선택한 요소 안에 자식 요소를 추가

itemListDiv.appendChild(newItemE);

→ itemListDiv에 자식요소 newItemE추가

<div id="itemList">

<div id="itedm_1"></div>

</div>

- createTextNode() : 선택한 요소에 텍스트를 추가


removeItem

○ 기존 HTML 엘리먼트 제거

- 해당 엘리먼트 부모의 removeChild() 메서드를 이용

- removeChild()

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

<script type="text/javascript">

var count = 0;

function addItem(){

count++;

var newItemE = document.createElement("div");

newItemE.setAttribute("id", "item_" + count);

/* <div id="item_1">

새로 추가된 아이템[1]<input type="button" value="삭제" onclick="removeItem('item_1');"/> */

var html = "새로 추가된 아이템[" + count +"]&nbsp;";

html += "<input type=\"button\" value=\"삭제\" onclick=\"removeItem('item_" + count + "');\"/>";

newItemE.innerHTML = html;

var itemListDiv = document.getElementById("itemList");

//누적

itemListDiv.appendChild(newItemE);

}

function removeItem(itemId){

var removeItem = document.getElementById(itemId);

removeItem.parentNode.removeChild(removeItem);

}


</script>

</head>

<body>

<h1>HTML DOM을 이용한 화면 변경</h1>

<hr/>

<input type="button" value="추가" onclick="addItem();">

<div id="itemList"></div>

</body>

</html>

예제 2 XML DOM 객체

○ 일반적으로 XML DOM객체를 더 많이 사용한다

○ xml파일을 가져오는 곳

 - DB 데이터

 - 공용데이터


① books.xml

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

<books>

<book>

<title>겨울왕국</title>

<author>디즈니</author>

</book>

<book>

<title>수지의 가수생활</title>

<author>EBS</author>

</book>

<book>

<title>이솝우화</title>

<author>미드</author>

</book>

<book>

<title>힐러리의 삶</title>

<author>클린턴</author>

</book>

</books>
○ DOM객체


② getBooksXML.jsp

displayBookList

○ documentElement

getElementsByTagName

- 특정 태그를 사용하는 요소들의 배열을 얻는다

- item(i)을 사용하여 자식노드에 접근한다

<script type="text/javascript" src="<%=cp%>/data/js/httpRequest.js"></script>

<script type="text/javascript">

function getBookList(){

//데이터를 읽기만 하므로 보내는 데이터는 없다

sendRequest("books.xml", null, displayBookList, "GET");

}


function displayBookList(){

if(httpRequest.readyState==4){

if(httpRequest.status==200){

//전달받은 XML을 DOM객체에 넣음

//responseXML : 전달받는 데이터가 xml

var Document=httpRequest.responseXML;

//DOM 객체에서 Elements추출

var booksE=Document.documentElement;

//book의 갯수 추출

var bookNL=booksE.getElementsByTagName("book");

//alert(bookNL.length);

//전체데이터 읽고 HTML로 출력

var html="";

html+="<ol>";

for(var i=0;i<bookNL.length;i++){

//하나의 book을 읽어냄

var bookE=bookNL.item(i);

var titleStr=bookE

.getElementsByTagName("title")

.item(0)

.firstChild

.nodeValue;

var authorStr=bookE

.getElementsByTagName("author")

.item(0)

.firstChild

.nodeValue;

html+= "<li>"

+ titleStr

+"&nbsp;-&nbsp;"

+ authorStr+"</li>";

}

html+="</ol>";

document.getElementById("bookDiv").innerHTML=html;

}

}

}

window.onload=function(){

getBookList();

}

</script>

</head>


<body>

<h1 id="list">Book List</h1>

<hr/>

<div id="bookDiv" style="display:block; margin:0 auto;"></div>

</body>


예제 3
① newsTitleCSV.jsp

<style type="text/css">

div{

margin:auto;

border: 1px solid #0000ff;

width: 600px;

height: 70%;

padding: 10px;

}

</style>


<script type="text/javascript" src="<%=cp%>/data/js/httpRequest.js"></script>

<script type="text/javascript">

function newsTitle(){

sendRequest("newsTitleXML_ok.jsp", null, displayNewsTitle, "GET");

setTimeout(newsTitle, 1000);

}

function displayNewsTitle(){

if(httpRequest.readyState==4){

if(httpRequest.status==200){

var doc = httpRequest.responseXML;

var count = doc.getElementsByTagName("count")

.item(0)

.firstChild

.nodeValue;

//alert(count);

if(count>0){

var titleNL = doc.getElementsByTagName("title");

var htmlData = "<ol>";

for(var i=0;i<count;i++){

htmlData += "<li>"

+ titleNL.item(i).firstChild.nodeValue

+ "</li>";

}

htmlData += "</ol>";

var newsDiv = document.getElementById("news");

newsDiv.innerHTML = htmlData;

}

}else{

alert(httpRequest.status + ":" + httpRequest.statusText);

}

}

}

window.onload = function(){

newsTitle();

}

</script>


② newsTitleCSV_ok.jsp

<%@page import="java.util.Date"%>

<%@ page contentType="text/xml; charset=UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

request.setCharacterEncoding("UTF-8");

String cp = request.getContextPath();

%>

<%!

String newsTitle[] = {

"예은아빠 '박근혜 감옥 갔으니 됐다'는 말에 힘 빠지더...",

"황교안의 '축구장 유세', 선관위가 허용?",

"정관수술했는데 늦둥이가 이 말에 부모님 반응?",

"기승전 갱년기... 나는 열 시간을 울었다",

"타지키스탄 효녀 '또냐'에게 가족사진을 선물했다",

"'우파 전대협' 반문재인 대자보, 진짜 총학생회의 고민은?",

"MB의 주옥같은 명언과 '주어는 없다'는 나경원"

};

%>

<result>

<count><%=newsTitle.length %></count>

<data>

<%for(int i=0;i<newsTitle.length;i++){ %>

<title><%=newsTitle[i] + " | " + new Date() %></title>

<%} %>

</data>

</result>