[XML] DOM

2008. 1. 3. 17:19

DOM

DOM(Document Object Model)

  • W3C's definition

    "The Document Object Model is a platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents.

  • DOM 의 역할
    • dynamic access and update
      • XML/HTML 문서의 접근 및 수정 => 내용/구조/스타일 정보의 검색 및 수정
      • 대상 문서 : XML1.0 또는 HTML4.0, 기타 웹문서
      • 컨텐츠의 조작 : 문서 요소에서 text 등 컨텐츠의 검색/질의, 추가/수정/삭제
      • 구조의 탐색 및 조작 : 각 요소와 속성에 대한 검색/질의, 추가/수정/삭제
    • interface
      • 응용 프로그램 인터페이스 (API) - 각종 메소드 및 속성을 정의
      • 플랫폼 및 언어 중립적(스크립트 포함) : Java, JavaScript, ASP, ...
  • DOM level
    • DOM level 1 : 1998.10 W3C 표준안
    • DOM level 2 : 2000.11 W3C 표준안
    • DOM level 3 : 2001.8 W3C Working Draft

DOM and XML Parser

  • Parser 의 역할
    • XML 문서를 읽고 해석 : well-formed, valid 검사
    • 응용프로그램 개발시 파서 사용 이유
      • 파서가 메모리에 DOM 트리를 생성 : XML 문서트리와 일치
      • 세부적인 XML 문법으로부터 프로그램 격리

  • [참고] SAX 기반 Parser

DOM 구조적 모델

  • DOM 트리에서 노드/객체의 종류
    • Document : 문서 객체, 최상위 노드
    • Element, Attribute : 문서의 구조를 구성하고 있는 요소
    • Text : 컨텐츠의 내용, 항상 단말 노드
    • Collection : 일종의 노드 집합
  • DOM 트리의 예

    <parent>
        <child  id="123">text here</child>
     </parent>

     

  • 인터페이스(API)의 예
    • 객체의 속성과 메소드를 사용하기 위한 사양
    • DOM 인터페이스 예
      - 문서.childNodes[1].nodeName
      - 문서.firstChild.firstCild.firstCild.nodeName
      - 문서.firstChild.firstCild.firstCild.nodeValue
  • DOM Core Interface (Object Hierachy) 교재 p.414 (표9-3)

DOM 주요 API

  • DOM 인터페이스의 공통 속성
    • type, name, value
    • 예) Node 객체의 경우 nodeType, nodeName, nodeValue 속성
      • nodeType은 위 그림과 같이 여러 가지가 있다 (p.418 표 9-6, 9-7)
  • 주요 객체/속성/메소드 - 진행하면서 지속적으로 참조

    객체(Object)

    속성(Properties)

    메소드(methods) 

    Node 객체

    nodeName, nodeType, nodeValue, childNodes, parentNode, childNode, firstChild, lastChild, previousSibling, nextSibling, attributes, ownerDocument, ..., 
    (
    text, xml) [표9-8]

    [표9-10] 노드 정보 구하기
    getNodeName, ..., getAttributes, ...
    [표 9-11] 문서 조작
    appendChild, insertBefore,
    removeChild, replaceChild, cloneNode
    [표 9-12] 트리 순회 관련
    getParentNode, getChildNode, ...
    hasChildNodes, ...

    Document 객체

    doctype,
    documentElement, implementation, ...

    (async, readyState)
    * W3C 표준이 아니라  MS에서 제공하는 인터페이스

    [표9-13] 문서관련 정보
    egtDoctype, getImplementation, ...
    [표 9-14] 트리 순회 관련
    getDocumentElement, getElemenmtByID,
    getElementByTagName, ...
    [표 9-15] 문서 작성
    createElement, createAttribute, createTextNode, createCDATASection, createComment, createEntityReference, ...

    DOMImplementation 객체

     

    [표 9-16] hasFeature, createDocument, ...

    DocumentFragment 객체

    * Node 객체와 동일

    * Node 객체와 동일

    NodeList 객체

    length

    [표 9-17] getLength, item

    Element 객체

    tagName

    [표 9-18] Element의 속성에 접근
    getAttribute, setAttribute, getAttributeNode, setAttributeNode, removeAttribute, ...,
    [표 9-18]Element 객체에 접근
    getTagName, hasAttribute, ...

    NamedNodeMap 객체

    length

    [표 9-19] getNamedItem, setNamedItem, removeNamedItem, item, getLength

    Attribute 객체

    name, value

    [표 9-20] getName, getValue, setValue, ...

    CharacterData 객체

    data, length

    [표 9-21] appendData, deleteData, insertData, replaceData, substringData, ...

DOM 프로그래밍 시작 - Document 객체

  • 문서 객체 새로 만들기 : DOMDocument 객체를 생성
    • Msxml.DOMDocument 객체를 새로 만들기
    • 또는 HTML에서 <xml> 태그 이용

    JavaScript (JScript)

    <Script language="Javascript">
       
    var xdoc1,xdoc2
       
    xdoc1 = new ActiveXObject("Msxml.DOMDocument");
       
    xdoc2 = new ActiveXObject("Msxml.DOMDocument");
        ...
    xdoc1.load("ex08.xml");  xdoc2.load("ex09.xml");
    </script>
    VBScript 의 경우 <Script language="VbScript">
      Dim xdoc1,xdoc2
      Set xdoc1 = CreateObject("Msxml.DOMDocument")
      Set xdoc2 = CreateObject("Msxml.DOMDocument")
      ...
    xdoc1.load("ex08.xml"); xdoc2.load("ex09.xml");
    </Script>

    HTML에서 <xml>  태그 이용

    - MSXML 파서 설치안한 경우

    <HTML> <HEAD>
        <Script language="Javascript">
            xdoc.load("ex08.xml");    </script>
    </HEAD>
    <BODY>
        <xml id="xdoc1"></xml>
        <xml id="xdoc2" src="ex09.xml"></xml>
    </BODY> </HTML>

    Java의 경우

    import java.xml.parsers.*;
    ...
    class xxxxxx
    {
      public static void main(String[] args) throws Exception
      {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder  db = dbf.newDocumentBuilder();
        Document  xdoc1 = db.parse(new FileInputStream(arg[0]));
    ...

  • 기존의 XML 문서 읽기
    • DOMDocument 객체 읽기 - async 속성, load 메소드, xml 속성 : MSXML에서 제공
    MSXML 파서 설치한 경우   MSXML 파서 설치안한 경우  
    <HTML>
    <HEAD>
    <Script language="Javascript">
    function xload0()
    {
       
    var xdoc = new
            ActiveXObject("Msxml.DOMDocument");
        xdoc.
    async = false;    xdoc.load("ex08.xml");
       
    alert(xdoc.xml);
    }
    </script>
    </HEAD>
    <BODY>
    <input type="button" value="XML 로드0"
        onClick="xload0()">
    </BODY>
    </HTML>  
    <HTML>
    <HEAD>
    <Script language="Javascript">
    function xload1()
    {
        xdoc.async = false;
        xdoc.load("ex08.xml");

         alert(xdoc.xml);
    }
    </script>
    </HEAD>
    <BODY>
    <input type="button" value="XML 로드1"
        onClick="xload1()">
    <xml id="xdoc"></xml>
    </BODY>
    </HTML>
    VBScript 의 경우
    <Script language="VbScript">
      Dim xdoc
      Set xdoc = CreateObject("Msxml.DOMDocument")
      xdoc.
    async = False;
      xdoc.
    load("ex08.xml");  MsgBox  xdoc.xml
    </Script>
  • 신규 XML 문서의 작성
    • loadXML 메소드  
     xdoc.async = false;
     xdoc.
    loadXML( "<book><title>XML 입문</title><author>일지매</author></book>");
     alert(xdoc.xml);  
     xdoc.async = false;
     xdoc.
    loadXML( "<book> <title> XML 입문 </title> <author> 일지매 </author> </book>");
     alert(xdoc.xml);  
  • 공백의 처리 : preserveWhiteSpace 속성
     xdoc.async = false;
     xdoc.preserveWhiteSpace = true;
     xdoc.loadXML( "<book> <title> XML 입문 </title> <author> 일지매 </author> </book>");
     alert(xdoc.xml);  
     xdoc.async = false;
     xdoc.preserveWhiteSpace = true;
     xdoc.load("ex08.xml");
     alert(xdoc.xml);  
  • XML 문서의 저장 : save 메소드
  • 에러 처리 : parseError 객체
    • parseError.errorCode, parseError.line, parseError.linepos, parseError.reason
     xdoc.async = false;
     xdoc.loadXML( "<book> <title> XML 입문 </title> <author> 일지매 </authors> </book>");
     alert(xdoc.xml);  
     xdoc.async = false;
     xdoc.loadXML( "<book> <title> XML 입문 </title> <author> 일지매 </authors> </book>");
     if (xdoc.parseError)
        alert("에러 위치 : " + xdoc.parseError.line + "번째 라인 " + xdoc.parseError.linepos 
                  + "번째 문자 에러 이유 : " + xdoc.parseError.reason);
     else
    alert(xdoc.xml);  
  • 루트 노드 찾기 (루트 에리먼트)
    • documentElement 속성
     xdoc.async = false;
     xdoc.load("ex08.xml");
     var xroot = xdoc.
    documentElement;
     alert(xroot.nodeName);  
     xdoc.async = false;
     xdoc.loadXML( "<book> <title> XML 입문 </title> <author> 일지매 </author> </book>");

     var xroot = xdoc.
    documentElement;
     alert(xroot.nodeName);  

Node 객체의 정보구하기 - Node 객체

  • 속성 : nodeName, nodeType, nodeValue, attributes, text 속성
  • nodeType
    • 1 (element), 2 (attribute), 3 (text) , 4 (CDATA), 5 (Entity Reference)...
  •  xdoc.load("ex08.xml");
     var xroot = xdoc.documentElement;
     alert('nodeName: '+xroot.nodeName+' nodeType: '+xroot.nodeType+
           ' nodeValue: '+xroot.nodeValue+' attributes: '+xroot.attributes.length);
     alert('xroot.text : ' + xroot.text);
     

실습 프로그램

  • 파일 LOAD 및 DOM 명령 실행 (교재 s20-03.htm 과 s20-05.htm 혼합)

    XML 파일 경로를 직접 입력하거나  '찾아보기'로 선택, 'LOAD'로 파일을 메모리에 로드
    경로 :  =>

    또는 미리 작성되어 있는 파일 사용하기  

    사용하고자 하는 DOM 구문을 아래에 입력하고 '확인' 버튼을 클릭  (예 : xdoc.text, xdoc.documentElement.firstChild.nodeName, ...) 구문 :    

     <SCRIPT language="Javascript">
            var xdoc, rootNode;
            function
    FileLoad(filename)
            {
                    xdoc = new ActiveXObject("Msxml.DOMDocument");
                    xdoc.async = false;
                    if (filename) xdoc.load(
    filename);
                    else xdoc.load(
    "file://"+path.value);
                    if (xdoc.parseError.errorCode != 0)
                        alert("파일을 메모리로 로드하는데 실패하였습니다 : " + xdoc.parseError.reason);
     
                    rootNode = xdoc.documentElement;
                    alert("[파일로드 성공] 루트 엘리먼트 : " + rootNode.nodeName);
            }
            function Execute()
            {
                    var selectionString;
                    try {
                            selectionString = eval(syntax.value);
                    } catch(e) {
                            selectionString = null;
                    }
                    alert(selectionString);
            }
    </SCRIPT>  
     ...
    <BODY>
     ... 경로 : <input  type="file"  size="40"  id="
    path">
         <input  type="button"  value="LOAD"  onclick="
    FileLoad()">
     ... 미리 작성되어 있는 파일
         <input  type="button"  value="서점 책 list"  onclick="
    FileLoad("ex08.xml")">
     ... 구문 : <input  size="50"  id="
    syntax"  value="xdoc.">&nbsp;
         <input  type="button" onclick="
    Execute()" value=확인>
     ...
    </BODY>

Posted by 나비:D
:
BLOG main image
by 나비:D

공지사항

카테고리

분류 전체보기 (278)
Programming? (0)
---------------------------.. (0)
나비의삽질 (5)
Application (177)
SQL (51)
Web (27)
etc. (14)
Omnia (0)
---------------------------.. (0)

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

달력

«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Total :
Today : Yesterday :