달력

4

« 2024/4 »

  • 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

'DOM'에 해당되는 글 3

  1. 2007.04.19 DOM 이해하기 (한글)
  2. 2007.03.20 DOM(Document Object Model)
  3. 2007.02.14 03. XML 문서의 처리 - DOM
2007. 4. 19. 11:37

DOM 이해하기 (한글) 즐겨찾기/공부2007. 4. 19. 11:37

DOM 이해하기 Tutorial

https://www.ibm.com/developerworks/kr/library/tutorial/x-udom/index.html


from : IBM developerWorks
:
Posted by 뽀기
2007. 3. 20. 10:36

DOM(Document Object Model) 그거/Tech2007. 3. 20. 10:36

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>

'그거 > Tech' 카테고리의 다른 글

JSTL(JavaServer Pages Standard Tag Library)  (0) 2007.03.29
Velocity  (0) 2007.03.29
패턴과 프레임워크  (0) 2007.03.14
Crossing borders: JavaScript의 특징 (한글)  (0) 2007.03.13
JSON vs. XML  (0) 2007.03.13
:
Posted by 뽀기
2007. 2. 14. 17:48

03. XML 문서의 처리 - DOM 그거/Tech2007. 2. 14. 17:48

DOM ( Document Object Model)

DOM level 0 : HTML ver.3.x를 대상으로 한 비공식 버전
DOM level 1 : Node, Element, Attribute로 구성되는 기본 구조
DOM level 2 : DOM level 1의 보강
DOM level 3 :

- Node
  DOM의 기본 구성 요소
  문서 그 자체, element, attribute, text, 처리 지시문, 주석문 등이 모두 Node interface의 특별한 경우로 인식됨

  <?xml version="1.0"?>
  <friend>
   <handle degree="close">Harold</handle>
  </friend>

  하나의 문서 노드
  두 개의 element 노드(friend와 handle)
  네 개의 텍스트 노드(close, Harold, handle element의 앞/뒤 줄바꿈)
  하나의 애트리뷰트 노드(degree)

  document - root element(firned) +-  text(whitespace)
                                               +-  element(handle)      - text(Harold)
                                               |    |
                                               |    +- attribute(degree) - text(close)
                                               +- text(whitespace)

- DOM에 정의된 interface
  Node                     - 모든 노드 타입에 대한 상위 클래스. getParentNode(), getNodeName(), insertBefore(), removeChild()...
  Document                 - 거의 모든 타입의 노드들을 포함하는 노드, 문서 자체를 대표하는 interface. createElement(), createTextNode() ...
  Element                  - element를 대표하는 타입. Attr 노드와 관련될 수 있는 노드 타입. getElementsByTagName() ...
  Attr                     - 자식으로 Text 노드나 EntityReference 노드를 가질 수 있다.
  Text                     - 마크없이 없는 문자열. 혼합 컨텐츠에 대한 텍스트 노드는 Text와 Element 노드로 분리될 수 있다.
  CDATASection             - 마크업 기호(<, >)를 단순한 텍스트로 취급
  DocumentType             - DTD 내부에 문자열로 표현된 모든 정보를 포함하는 노드 타입.
  Comment                  -
  Notation                 -
  Entity                   -
  EntityReference          -
  ProcessingInstruction    -

  DocumentFragment         - 이 Node 인터페이스의 구현은 자신의 고유 메소드를 갖는 대신에 옮기고자 하는 노드의 그룹을 포함하는 컨테이너나 작은 문서의 역할
  DOMImplementation        - hasFeature() 메소드를 사용해서 지원되는 기능의 가동 여부를 확인할 수 있다.
  DOMException, ExceptionCode - application 에서 발생한 예외 사항에 대한 보고를 위해 사용.
  NodeList                 - Node의 자식들처럼 정렬된 목록을 제공
  NamedNodeMap             - 한 element가 포함하는 attribute들 처럼 이름에 의해 접근 가능한, 정렬되지 않은 목록을 제공.

- DOM 관련 권고안들
  DOM level 2.0 Traversal and Range
    : XML 문서에 대한 효율적인 조회를 위한 NodeItreator 와 TreeWalker의 두 가지 새로운 interface가 포함.
  DOM level 2.0 HTML
    : Core 권고안 내에 HTMLDocument와 HTMLFormElement와 같은 HTML 문서에 대한 정의를 포함.
  DOM level 2.0 Style Sheets
    : CSS나 CSS 내부에 포함된 데이터의 처리를 위한 interface에 대한 정의를 제공.
  DOM level 2.0 Views
    : 문서의 버전을 구별하는 방법을 제공(DOM level 3.0 에서 삭제된 모듈)
  DOM level 2.0 Events
    : 마우스 클릭과 같은 액션이 발생했을 때 객체의 행동을 결정하는 방법을 제공하며, 해당 객체의 상휘/하위의 모든 객체에 영향을 미친다.
  DOM level 3.0 Load and Save
    : 문서의 적재와 저장에 대한 interface를 제공.
  DOM level 3.- Validation
    : Document 객체가 특정 문법과 연관되어 유효성을 갖는지 검사하는 방법을 제공.
  DOM level 3.0 XPath
    : 문서 내에서 노드의 위치를 찾아내거나 기술하기 위해 XPath 문법을 사용해 높은 유연성을 제공. DOM 에서의 XPath 1.0 이용 방법을 정의

- DOM interface 구현
  Java => JAXP, Apache, Xerces-Java
  C++  => MS Visual C++ .NET - COM과 MSXML 4.0
  VB   => MS VB .NET - MSXML 4.0
  Perl => Apache Xerces
  PHP  => PHP 4.2.1 또는 이후 버전

- Java를 이용한 XML 문서의 파싱

  import javax.xml.parsers.DocumentBuilder;
  import javax.xml.parsers.DocumentBuilderFactory;
  import java.io.File;
  import org.w3c.dom.Document;
  import org.w3c.dom.DOMImplementation;

  public class ActivityListing {
   public static void main(String[] args) {
  File docFile = new FIle("activities.xml");
  Document doc = null;

  try {
   DocumentBuilderFactory dbf = DocumentBuilderFactory.netInstance();
   DocumentBuilder db = dbf.newDocumentBuilder();
   doc = db.parse(docFile);

   DOMImplementation domImpl = doc.getImeplementation();

   if( domImpl.hasFeature("Core", "2.0") ) {
    System.out.println("2.0 is supported");
   } else {
    System.out.println("2.0 is not supported");
   }

   if( domImpl.hasFeature("Core", "5.0") ) {
    System.out.println("5.0 is supported");
   } else {
    System.out.println("5.0 is not supported");
   }
  } catch(Exception e) {
   System.out.println("Problem parsing the file.");
  }
 }
  }
 
  ELEMENT_NODE                = 1
  ATTRIBUTE_NODE              = 2
  TEXT_NODE                   = 3
  CDATA_SECTION_NODE          = 4
  ENTITY_REFERENCE_NODE       = 5
  ENTITY_NODE                 = 6
  PROCESSING_INSTRUCTION_NODE = 7
  COMMENT_NODE                = 8
  DOCUENT_NODE                = 9
  DOCUMENT_TYPE_NODE          = 10
  DOCUMENT_FRAGMENT_NODE      = 11
  NOTATION_NODE               = 12

- Document
  Element
  Child   - 아래 level
  Sibling - 같은 level
  getFirstChild()
  getNextSibling()
  getElementsByTagName()
  getElementById()
  getOwnerDocument()
  .
  .
  .
  .

  API 참조
  javax.xml.*
  org.w3c.dom(interface 정의들)
  org.xml.*

'그거 > Tech' 카테고리의 다른 글

05. XML 스트림 (SAX)  (0) 2007.02.14
04. DOM의 활용(고급편)  (0) 2007.02.14
02. XML 문서와 application의 설계  (0) 2007.02.14
01. XML 문서의 기본 구조  (0) 2007.02.14
유닉스 팁: 10가지 유닉스 사용 습관 (한글)  (0) 2007.02.08
:
Posted by 뽀기