1 / 59

DOM 이야기

DOM 이야기. DOM (Document Object Model). Tree-based API Parsing 후에 Memory 상에 문서전체의 Tree 구조를 만들어 사용 장점 Tree 구조를 가지므로 처리가 용이하다. 몇 번이고 원하는 부분을 추가 및 수정 가능 문서의 구조가 충실히 보존돼야 하는 경우( ex:XML Editor..) 단점 메모리상에 DataStructure 를 만들기 때문에 큰 문서에는 적당하지 않다 DOM 구조를 생성하는데 시간이 오래 걸린다. DOM !!!.

Download Presentation

DOM 이야기

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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. DOM Tree XML Processing Model (DOM) • DOM XML File DTD Application Parse XML Parser Errors Process xml programming

  5. DOM의 정의 • DOM • XML과 HTML에 대한 programmatic interface를 정의 xml programming

  6. Processing Steps • Parse 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 제목 </item> </library> Document <library> <?xml version="1.0"?> “주석" <item> <item> "CD 제목" type type “책 제목" “cd“ "book" xml programming

  8. DOM의 생성 과정 • JAXP에서 xml programming

  9. DOM API 살펴보기 • org.w3c.dom Package • Interfaces • Element • 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 • XML문서를 구성하는 모든 요소를 상징하는 객체이다. • 모든 객체의 공통적인 특성을 모아 놓은 추상화된 객체라고 할 수 있다. • Document • XML문서의 Root Element의 바로 위에 위치하며, 문서 전체의 Root객체 역할을 한다. • 일종의 가상 객체라고 할 수 있다. • Element • XML문서에서 가장 중요하고 기본이 되는 단위(Unit) xml programming

  12. 삼총사의 역할 • Node • 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. 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 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 namespaceURI 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 () • 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.StringnodeValue) • void setPrefix (java.lang.String prefix) xml programming

  19. Method 분류 #2 • Node를 조작하는 method • Node appendChild (NodenewChild) • Adds the node newChild to the end of the list of children of this node. • Node insertBefore (NodenewChild, NoderefChild) • Inserts the node newChild before the existing child node refChild. • Node removeChild (NodeoldChild) • Removes the child node indicated by oldChild from the list of children, and returns it. • Node replaceChild (NodenewChild, NodeoldChild) • 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 () • 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 <name> <given>lee</given> <family>lim</family> </name> • Element name의 child??? • Text : “\n” • Element : given • Text : “\n” • Element : family • Text : “\n” xml programming

  22. Relationship null getPreviousSibling() Text null getPreviousSibling() 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. Node Types xml programming

  24. NodeName과 NodeValue 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.StringelementId) • Returns the Element whose ID is given by elementId . • NodeList getElementsByTagName (java.lang.Stringtagname) • 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 (StringnamespaceURI, StringlocalName) • Returns a NodeList of all the Elements with a given local name and namespaceURI 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 (StringnamespaceURI, StringqualifiedName) • Creates an attribute of the given qualified name and namespaceURI. • 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.StringtagName) • Creates an element of the type specified. • Element createElementNS (StringnamespaceURI, StringqualifiedName) • Creates an element of the given qualified name and namespaceURI. • 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 (StringnamespaceURI, StringlocalName) • Retrieves an Attr node by local name and namespaceURI. • String getAttributeNS (StringnamespaceURI, StringlocalName) • Retrieves an attribute value by local name and namespaceURI. • void setAttribute (java.lang.String name, java.lang.String value) • Adds a new attribute. • Attr setAttributeNode (AttrnewAttr) • Adds a new attribute node. • Attr setAttributeNodeNS (Attr newAttr) • Adds a new attribute. xml programming

  32. • void setAttributeNS (StringnamespaceURI, StringqualifiedName, 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 (StringnamespaceURI, StringlocalName) • Returns true when an attribute with a given local name and namespaceURI 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 (StringnamespaceURI, StringlocalName) • Removes an attribute by local name and namespaceURI. 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 (StringnamespaceURI, StringlocalName) • Returns a NodeList of all the Elements with a given local name and namespaceURI 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 • Comment • Text • CDATASection • DocumentType • DocumentFragment • Entity • Notation • ProcessingInstruction xml programming

  36. Document DocumentType <?xml version=“1.0” ?> <!DOCTYPE book-order SYSTEM “book.dtd”> <book-order> <customer>Lee</customer> <shop>jaelee</shop> <goods> </book> <name>XMLBook</name> </book> </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 (intindex) • Returns the indexth item in the collection. xml programming

  39. NamedNodeMap • Int getLength () • Node item (intindex) • Node getNamedItem (java.lang.Stringname) • Retrieves a node specified by name. • Node removeNamedItem (java.lang.Stringname) • Removes a node specified by name. • Node setNamedItem (Nodearg) • Adds a node using its nodeName attribute. • Node getNamedItemNS (StringnamespaceURI, StringlocalName) • Node setNamedItemNS (Nodearg) • Node removeNamedItemNS (StringnamespaceURI, StringlocalName) 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다루기 • Inserting • Deleting • Replacing • Node 생성하기 xml programming

  47. 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 Text “jung” shop “jungang” goods book name “xmlbook” xml programming

  48. Node의 구조 정보 얻기 <?xml version=“1.0” ?> <가족> \n <남편>조성민</남편> <아내>최진실</아내> </가족> Text : “\n” Element : 남편 Text : “조성민” Element : 가족 Text : “\n” Element : 아내 Text : “최진실” Text : “\n” xml programming

  49. 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

More Related