Download presentation
Presentation is loading. Please wait.
1
DOM 이야기 xml programming
2
DOM (Document Object Model)
Tree-based API Parsing 후에 Memory상에 문서전체의 Tree구조를 만들어 사용 장점 Tree구조를 가지므로 처리가 용이하다. 몇 번이고 원하는 부분을 추가 및 수정 가능 문서의 구조가 충실히 보존돼야 하는 경우(ex:XML Editor..) 단점 메모리상에 DataStructure를 만들기 때문에 큰 문서에는 적당하지 않다 DOM구조를 생성하는데 시간이 오래 걸린다. xml programming
3
DOM !!! DHTML의 호환성 문제 표준 문서 객체 정의 필요성 제기
문서 편집기와 문서 저장소를 위한 API들이 영향을 줌 논리적인 문서 구조를 정의 응용프로그램이 문서에 접근하는 표준 방식을 확립 ‘객체지향’ 개념 기반 xml programming
4
XML Processing Model (DOM)
XML File DTD Application Parse XML Parser Errors DOM Tree Process xml programming
5
DOM의 정의 DOM XML과 HTML에 대한 programmatic interface를 정의 xml programming
6
Processing Steps Parse the document Process the document
Parser builds a DOM tree Process the document Using the DOM API Do something with the data Display it Produce a report Transcode it ... xml programming
7
XML 문서 Tree <?xml version="1.0"?> <library>
<!-- 주석 --> <item type="book"> 책 제목 </item> <item type="cd"> CD 제목 </library> Document <?xml version="1.0"?> <library> “주석" <item> <item> type “책 제목" type "CD 제목" "book" “cd“ xml programming
8
DOM의 생성 과정 JAXP에서 xml programming
9
DOM API 살펴보기 org.w3c.dom Package Interfaces Element Attr Entity
EntityReference NamedNodeMap Node NodeList Notation ProcessingInstruction Text Attr CDATASection CharacterData Comment Document DocumentFragment DocumentType DOMImplementation xml programming
10
DOM의 삼총사 Node Document Element xml programming
11
삼총사의 특징 Node Document Element XML문서를 구성하는 모든 요소를 상징하는 객체이다.
모든 객체의 공통적인 특성을 모아 놓은 추상화된 객체라고 할 수 있다. Document XML문서의 Root Element의 바로 위에 위치하며, 문서 전체의 Root객체 역할을 한다. 일종의 가상 객체라고 할 수 있다. Element XML문서에서 가장 중요하고 기본이 되는 단위(Unit) xml programming
12
삼총사의 역할 Node Document Element
Find information about the Node, such as its value, name, and type Read, update, and delete information Find children, parent, and sibling Node information Document Query for information about the document, such as its name, entities, and notations Query for information about the implementation, such as what version of the DOM core is supported Create documents, DocumentFragments, Elements, Nodes, Attributes, Comments, and so on. Traverse the document tree Element Access and manipulate the attributes of the Element Access the children of the Element Access the tag of the Element xml programming
13
삼총사의 관계 : Interface의 상속관계
DOMimplementation Attr NamedNodeMap Comment CharacterData NodeList Text CDATASection DocumentType DocumentFragment Node Document DOMException Element Entity EntityReference Notation ProcessingInstruction xml programming
14
<?xml version=“1.0”?>
… Document=Node <?xml version=“1.0”?> book-order Element = Node customer Element = Node “jung” Text = Node shop “Jungang” goods book name “XMLBook” xml programming
15
부모/자식 Relationships in the Document
Element Text Comment CDATASection ProcessingInstruction Element Text EntityReference CDATASection ProcessingInstruction Comment EntityReference Entity ProcessingInstruction Comment CDATASection xml programming
16
Node Node자체의 정보를 얻거나 정하는 method Node를 조작하는 method
Related Node를 얻는 method method 분류해보기!!! 직접 Node의 method를 분류해 봅시다. xml programming
17
Method 분류 #1 Node자체의 정보를 얻거나 정하는 method NamedNodeMap getAttributes ()
A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise. String getLocalName () Returns the local part of the qualified name of this node. String getNamespaceURI () The namespace URI of this node, or null if it is unspecified. String getNodeName () The name of this node, depending on its type; see the table above. Short getNodeType () A code representing the type of the underlying object, as defined above. String getNodeValue () The value of this node, depending on its type; see the table above. String getPrefix () The namespace prefix of this node, or null if it is unspecified. xml programming
18
… boolean hasAttributes () boolean hasChildNodes ()
Returns whether this node (if it is an element) has any attributes. boolean hasChildNodes () Returns whether this node has any children. boolean isSupported (java.lang.String feature, java.lang.String version) Tests whether the DOM implementation implements a specific feature and that feature is supported by this node. void setNodeValue (java.lang.String nodeValue) void setPrefix (java.lang.String prefix) xml programming
19
Method 분류 #2 Node를 조작하는 method Node appendChild (Node newChild)
Adds the node newChild to the end of the list of children of this node. Node insertBefore (Node newChild, Node refChild) Inserts the node newChild before the existing child node refChild. Node removeChild (Node oldChild) Removes the child node indicated by oldChild from the list of children, and returns it. Node replaceChild (Node newChild, Node oldChild) Replaces the child node oldChild with newChild in the list of children, and returns the oldChild node. Node cloneNode (boolean deep) Returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes. void Normalize () xml programming
20
Method 분류 #3 Related Node를 얻는 method getChildNodes () getFirstChild ()
A NodeList that contains all children of this node. getFirstChild () The first child of this node. getLastChild () The last child of this node. getNextSibling () The node immediately following this node. getPreviousSibling () The node immediately preceding this node. getParentNode () The parent of this node. Document getOwnerDocument () The Document object associated with this node. xml programming
21
… sample.xml Element name의 child??? <name>
<given>lee</given> <family>lim</family> </name> Element name의 child??? Text : “\n” Element : given Element : family xml programming
22
Relationship xml programming null getPreviousSibling() Text null
getNextSibling() getPreviousSibling() getPreviousSibling() Element Text getPreviousSibling() getNextSibling() getNextSibling() Element Text getPreviousSibling() getNextSibling() getPreviousSibling() Element Text getNextSibling() getPreviousSibling() getNextSibling() getNextSibling() Text null getNextSibling() null xml programming
23
ProcessingInstruction
Node Types 노드 타입 노드 타입 상수 값 Element ELEMENT_NODE 1 Attr ATTRIBUTE_NODE 2 Text TEXT_NODE 3 CDATASection CDATA_SECTION_NODE 4 EntityReference ENTITY_REFERENCE_NODE 5 Entity ENTITY_NODE 6 ProcessingInstruction PROCESSING_INSTRUCTION_NODE 7 Comment COMMENT_NODE 8 Document DOCUMENT_NODE 9 DocumentType DOCUMENT_TYPE_NODE 10 DocumentFragment DOCUMENT_FRAGMENT_NODE 11 Notation NOTATION_NODE 12 xml programming
24
ProcessingInstruction
NodeName과 NodeValue 노드 타입 nodeName nodeValue Element 태그 이름 Null Attr 속성 이름 속성 값 Text #text 텍스트 노드의 내용 CDATASection #cdata-section CDATASection 내용 EntityReference 엔티티 참조 이름 Entity 엔티티 이름 ProcessingInstruction 타겟 이름 타겟을 제외한 내용 Comment #comment 코멘트 내용 Document #document DocumentType 문서형 이름 DocumentFragment #document-fragment Notation 노테이션 이름 xml programming
25
Document Document에 대한 정보를 얻는 method
Document에 있는 element를 조건에 따라 얻는 method Node 생성에 관련된 method method 분류해보기!!! 직접 Node의 method를 분류해 봅시다. xml programming
26
Method 분류 #1 Document에 대한 정보를 얻는 method Document Type getDoctype ()
The Document Type Declaration (see DocumentType ) associated with this document. Element getDocumentElement () This is a convenience attribute that allows direct access to the child node that is the root element of the document. DOMImplementation getImplementation () The DOMImplementation object that handles this document. xml programming
27
Method 분류 #2 Document에 있는 element를 조건에 따라 얻는 method
Element getElementById (java.lang.String elementId) Returns the Element whose ID is given by elementId . NodeList getElementsByTagName (java.lang.String tagname) Returns a NodeList of all the Elements with a given tag name in the order in which they would be encountered in a preorder traversal of the Document tree. NodeList getElementsByTagNameNS (String namespaceURI, String localName) Returns a NodeList of all the Elements with a given local name and namespace URI in the order in which they would be encountered in a preorder traversal of the Document tree. Node importNode (Node importedNode, boolean deep) Imports a node from another document to this document. xml programming
28
Method 분류 #3 Node 생성에 관련된 method
Attr createAttribute (java.lang.String name) Creates an Attr of the given name. Attr createAttributeNS (String namespaceURI, String qualifiedName) Creates an attribute of the given qualified name and namespace URI. CDATASection createCDATASection (java.lang.String data) Creates a CDATASection node whose value is the specified string. Comment createComment (java.lang.String data) Creates a Comment node given the specified string. DocumentFragment createDocumentFragment () Creates an empty DocumentFragment object. xml programming
29
… Element createElement (java.lang.String tagName)
Creates an element of the type specified. Element createElementNS (String namespaceURI, String qualifiedName) Creates an element of the given qualified name and namespace URI. EntityReference createEntityReference (java.lang.String name) Creates an EntityReference object. ProcessingInstruction createProcessingInstruction (String target, String data) Creates a ProcessingInstruction node given the specified name and data strings. Text createTextNode (java.lang.String data) Creates a Text node given the specified string. xml programming
30
Element Attribute와 관련된 method Child Element를 얻는 method
Element의 Tag를 얻어 오는 method method 분류해보기!!! 직접 Node의 method를 분류해 봅시다. xml programming
31
Method 분류 #1 Attribute와 관련된 method
String getAttribute (java.lang.String name) Retrieves an attribute value by name. Attr getAttributeNode (java.lang.String name) Retrieves an attribute node by name. Attr getAttributeNodeNS (String namespaceURI, String localName) Retrieves an Attr node by local name and namespace URI. String getAttributeNS (String namespaceURI, String localName) Retrieves an attribute value by local name and namespace URI. void setAttribute (java.lang.String name, java.lang.String value) Adds a new attribute. Attr setAttributeNode (Attr newAttr) Adds a new attribute node. Attr setAttributeNodeNS (Attr newAttr) xml programming
32
… void setAttributeNS (String namespaceURI, String qualifiedName, String value) Adds a new attribute. boolean hasAttribute (java.lang.String name) Returns true when an attribute with a given name is specified on this element or has a default value, false otherwise. boolean hasAttributeNS (String namespaceURI, String localName) Returns true when an attribute with a given local name and namespace URI is specified on this element or has a default value, false otherwise. void removeAttribute (java.lang.String name) Removes an attribute by name. Attr removeAttributeNode (Attr oldAttr) Removes the specified attribute node. void removeAttributeNS (String namespaceURI, String localName) Removes an attribute by local name and namespace URI. xml programming
33
Method 분류 #2 Child Element를 얻는 method
NodeList getElementsByTagName (java.lang.String name) Returns a NodeList of all descendant elements with a given tag name, in the order in which they would be encountered in a preorder traversal of the Element tree. NodeList getElementsByTagNameNS (String namespaceURI, String localName) Returns a NodeList of all the Elements with a given local name and namespace URI in the order in which they would be encountered in a preorder traversal of the Document tree, starting from this node. xml programming
34
Method 분류 #3 Element의 Tag를 얻어 오는 method java.lang.String getTagName ()
The name of the element. xml programming
35
다른 Node Attr CharacterData DocumentType DocumentFragment Entity
Comment Text CDATASection DocumentType DocumentFragment Entity Notation ProcessingInstruction xml programming
36
DocumentType DocumentType Document xml programming
<?xml version=“1.0” ?> <!DOCTYPE book-order SYSTEM “book.dtd”> <book-order> <customer>Lee</customer> <shop>jaelee</shop> <goods> </book> <name>XMLBook</name> </good> </book-order> <?xml version=“1.0”?> <!DOCTYPE book-order SYSTEM “book.dtd” DocumentType book-order Element customer Element “Lee” Text shop “jaelee” xml programming
37
추가 interface NodeList NamedNodeMap
These two interfaces exist to process lists of nodes xml programming
38
NodeList The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. 2 method Int getLength () The number of nodes in the list. Node item (int index) Returns the indexth item in the collection. xml programming
39
NamedNodeMap Int getLength () Node item (int index)
Node getNamedItem (java.lang.String name) Retrieves a node specified by name. Node removeNamedItem (java.lang.String name) Removes a node specified by name. Node setNamedItem (Node arg) Adds a node using its nodeName attribute. Node getNamedItemNS (String namespaceURI, String localName) Node setNamedItemNS (Node arg) Node removeNamedItemNS (String namespaceURI, String localName) xml programming
40
쉬어갑니다!! xml programming
41
DOM Parser 생성하기 3가지 생성방법 비교 DocumentBuilder를 이용해 Document를 생성해 사용한다.
JAXP에서 제안 DOMParser 클래스를 직접 생성해 parsing을 통해 Document를 얻어 사용한다. XML4J와 Oracle등에서 제안 XmlDocument.createXmlDocument를 사용해 Document를 생성해 사용한다. Java Project-X에서 제안 xml programming
42
JAXP에서 생성 DocumentBuilderFactory로 DocumentBuilder생성
DocumentBuilder로 Document생성 Ex: … DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = dbFactory.newDocumentBuilder(); Document doc = documentBuilder.parse(is); xml programming
43
XML4J에서 생성 XML4J나 Oracle의 DOMParser는 직접 생성해 사용가능 Ex: …
DOMParser myDOMParser = new DOMParser(); myDOMParser.parse(String uri); Document doc = myDOMParser.getDocument(); xml programming
44
Manipulating the DOM sample code
public void printElementValue(Element root, String tag) { Element child = root; NodeList childs = child.getElementByTagName(lastTag); for ( int=0; i<childs.getLength(); i++ ) System.out.println(childs.item(i).getValue()); } xml programming
45
Manipulating the DOM recursive module
public void processNode(Node n) { switch(n.getNodeType()) { case Node.ELEMENT_NODE : { handleThisNode(n); NodeList kids=n.getChildNodes(); if (kids != null) for(int i=0; i<kids.getLength(); i++) processNode(kids.item(i)); } xml programming
46
Node 다루기 Node 여행하기 Node의 상태 정보 얻기 Node의 구조 정보 얻기 Node다루기 Node 생성하기
Inserting Deleting Replacing Node 생성하기 xml programming
47
<?xml version=“1.0”?>
Node 여행하기 documentPrinter(Node node){ Switch(node.getNodeType()){ case: 도큐먼트 노드인 경우 1-1. XML선언출력 1-2. 자식이 있으면 재귀호출 1-3. case : 엘리먼트 노드인 경우 2-1. “<엘리먼트이름>” 출력 2-2. 자식이 있으면 재귀호출 2-3. “</닫는태크>” 출력 case : 텍스트 노드인 경우 3-1. “텍스트” 출력 3-2. 리턴 . } Document <?xml version=“1.0”?> book-order Element customer Element “jung” Text shop “jungang” goods book name “xmlbook” xml programming
48
Node의 구조 정보 얻기 xml programming <?xml version=“1.0” ?>
<남편>조성민</남편> <아내>최진실</아내> </가족> Text : “\n” Element : 남편 Text : “조성민” Element : 가족 Text : “\n” Element : 아내 Text : “최진실” Text : “\n” xml programming
49
Document Document xml programming book-order Element
DOCTYPE선언이 없는 경우 DOCTYPE선언이 있는 경우 Document Document book-order Element <!DOCTYPE book-order SYSTEM “book.dtd” DocumentType customer Element book-order Element “lee” Text customer Element shop “lee” Text “SoftBank” shop goods “SoftBank” goods <!DOCTYPE book-order SYSTEM “null” DocumentType xml programming
50
Node의 상태 정보 얻기 Node.getNodeType() Node.getNodeName()
Node.getNodeValue() Node.setNodeValue() xml programming
51
Node의 구조 정보 얻기 Node.getParentnode() xml programming
<?xml version=“1.0” ?> <name> <given>lee</given> <family>lim</family> </name> Text Element Text Element Text Element Text Text xml programming
52
Node다루기 Inserting Deleting Replacing Clone
Node.insertBefore(Node newNode, Node refChild) Node.appendChild(Node newChild) Deleting Node.removeChild(Node oldChild) Replacing Node.replaceChild(Node newChild, Node oldChild) Clone Node.cloneNode(boolean deep) xml programming
53
Inserting Node.insertBefore(Node newChild, Node refChild)
xml programming
54
… Node.appendChild(Node newChild) Node newChild xml programming
55
… appendChild vs insertBefore So…
appendChild(Node newChild) Adds the node newChild to the end of the list of children of this node. If the newChild is already in the tree, it is first removed. insertBefore(Node newChild, Node refChild) Inserts the node newChild before the existing child node refChild. If refChild is null, insert newChild at the end of the list of children. So… appendChild(newNode) = insertBefore(newNode, null) xml programming
56
Deleting Node.removeChild(Node oldChild) xml programming Child 1 Node
Child 3(oldChild) Child 4 xml programming
57
Replacing Node.replaceChild(Node newChild, Node oldChild)
Child 3(oldChild) Child 4 newChild xml programming
58
Clone cloneNode(boolean deep) Copy Boolean Shallow copy Deep copy
True : deep False : shallow xml programming
59
Node 생성하기 Element생성하기 Attribute생성하기 Text 생성하기
document.createElement(String TagName) Attribute생성하기 document.createAttribute(string Name) Text 생성하기 document.createTextNode(String data) xml programming
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.