dom 이야기
DESCRIPTION
DOM 이야기. DOM (Document Object Model). Tree-based API Parsing 후에 Memory 상에 문서전체의 Tree 구조를 만들어 사용 장점 Tree 구조를 가지므로 처리가 용이하다. 몇 번이고 원하는 부분을 추가 및 수정 가능 문서의 구조가 충실히 보존돼야 하는 경우( ex:XML Editor..) 단점 메모리상에 DataStructure 를 만들기 때문에 큰 문서에는 적당하지 않다 DOM 구조를 생성하는데 시간이 오래 걸린다. DOM !!!. - PowerPoint PPT PresentationTRANSCRIPT
xml programming 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) DOM
XML File
DTD
XML Parser
DOM Tree
ApplicationParse
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
<library>
Document
<item> <item>
<?xml version="1.0"?><library> <!-- 주석 --> <item type="book"> 책 제목 </item>
<item type="cd"> CD 제목 </item></library>
<?xml version="1.0"?><library> <!-- 주석 --> <item type="book"> 책 제목 </item>
<item type="cd"> CD 제목 </item></library>
"book"
type
“cd“
"CD 제목 "“ 책 제목 "type
“ 주석 "
<?xml version="1.0"?>
xml programming 8
DOM 의 생성 과정
JAXP 에서
xml programming 9
DOM API 살펴보기
org.w3c.dom Package Interfaces
Attr CDATASection CharacterData Comment Document DocumentFragment DocumentType DOMImplementation
Element Entity EntityReference NamedNodeMap Node NodeList Notation ProcessingInstruction Text
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
DOMimplementation
NamedNodeMapNamedNodeMap
NodeListNodeList
NodeNode
DOMExceptionDOMException
AttrAttr
CharacterDataCharacterData
DocumentTypeDocumentType
DocumentFragment
DocumentFragment
DocumentDocument
ElementElement
EntityEntity
EntityReferenceEntityReference
NotationNotation
ProcessingInstruction
ProcessingInstruction
CommentComment
TextText CDATASectionCDATASection
xml programming 14
…
book-order
customer
shop
goods
book
name
“XMLBook”
“jung”
“Jungang”
<?xml version=“1.0”?>
Document=Node
Element = Node
Element = Node
Text = Node
xml programming 15
부모 / 자식 Relationships in the Document
DocumentDocument
ElementElement ProcessingInstruction
ProcessingInstruction
CommentCommentTextText CDATASectionCDATASection
ElementElement TextText EntityReference
EntityReference
ProcessingInstruction
ProcessingInstruction
CDATASection
CDATASection
CommentComment
EntityReference
EntityReference
ProcessingInstruction
ProcessingInstruction
EntityEntity CommentComment CDATASection
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 ()• 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 ()
• 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
ElementElement
TextText
ElementElement
ElementElement
TextText
TextText
TextText
TextText
getPreviousSibling()
getNextSibling()
getPreviousSibling()
getPreviousSibling()
getPreviousSibling()
getPreviousSibling()
getPreviousSibling()
getNextSibling()
getNextSibling()
getNextSibling()
getNextSibling()
getNextSibling()
getPreviousSibling()
getNextSibling()
getPreviousSibling()
getNextSibling()
null
null
null
null
xml programming 23
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
NodeName 과 NodeValue
노드 타입 nodeName nodeValue
Element 태그 이름 Null
Attr 속성 이름 속성 값
Text #text 텍스트 노드의 내용
CDATASection #cdata-section CDATASection 내용
EntityReference 엔티티 참조 이름 Null
Entity 엔티티 이름 Null
ProcessingInstruction 타겟 이름 타겟을 제외한 내용
Comment #comment 코멘트 내용
Document #document Null
DocumentType 문서형 이름 Null
DocumentFragment #document-fragment Null
Notation 노테이션 이름 Null
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)
• Adds a new attribute.
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
Comment Text CDATASection
DocumentType DocumentFragment Entity Notation ProcessingInstruction
xml programming 36
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>
book-order
customer
shop
“Lee”
“jaelee”
<?xml version=“1.0”?>
Document
Element
Element
Text
<!DOCTYPE book-order SYSTEM “book.dtd”
DocumentType
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 다루기 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. 리턴 . . . }}
book-order
customer
shop
goods
book
name
“xmlbook”
“jung”
“jungang”
<?xml version=“1.0”?>
Document
Element
Element
Text
xml programming 48
Node 의 구조 정보 얻기
Element : 가족Element : 가족
Text : “\n”Text : “\n”
Element : 아내Element : 아내
Element : 남편Element : 남편
Text : “\n”Text : “\n”
Text : “\n”Text : “\n”
Text : “ 조성민”Text : “ 조성민”
Text : “ 최진실”Text : “ 최진실”
<?xml version=“1.0” ?>
< 가족 > \ n
< 남편 > 조성민 </ 남편 >
< 아내 > 최진실 </ 아내 >
</ 가족 >
xml programming 49
book-order
customer
shop
goods
“lee”
“SoftBank”
Element
Element
Text
Document
<!DOCTYPE book-order SYSTEM “book.dtd”DocumentType
book-order
customer
shop
goods
“lee”
“SoftBank”
Element
Element
Text
Document
<!DOCTYPE book-order SYSTEM “null”
DocumentType
DOCTYPE 선언이 없는 경우 DOCTYPE 선언이 있는 경우
xml programming 50
Node 의 상태 정보 얻기
Node.getNodeType()
Node.getNodeName()
Node.getNodeValue()
Node.setNodeValue()
xml programming 51
Node 의 구조 정보 얻기
Node.getParentnode()
ElementElement
TextText
ElementElement
ElementElement
TextText
TextText
TextText
TextText
<?xml version=“1.0” ?>
<name>
<given>lee</given>
<family>lim</family>
</name>
xml programming 52
Node 다루기
Inserting 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)
NodeNode refChildrefChild
newChildnewChild
xml programming 54
…
Node.appendChild(Node newChild)
NodeNode
newChildnewChild
xml programming 55
…
appendChild vs insertBefore 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)
NodeNode
Child 1Child 1
Child 4Child 4
Child 2Child 2
Child 3(oldChild)
Child 3(oldChild)
NodeNode
Child 1Child 1
Child 4Child 4
Child 2Child 2
xml programming 57
Replacing
Node.replaceChild(Node newChild, Node oldChild)
NodeNode
Child 1Child 1
Child 4Child 4
Child 2Child 2
Child 3(oldChild)
Child 3(oldChild)
newChildnewChild
NodeNode
Child 1Child 1
Child 4Child 4
Child 2Child 2
newChildnewChild
xml programming 58
Clone
cloneNode(boolean deep) Copy
• Shallow copy• Deep copy
Boolean• True : deep• False : shallow
xml programming 59
Node 생성하기
Element 생성하기 document.createElement(String TagName)
Attribute 생성하기 document.createAttribute(string Name)
Text 생성하기 document.createTextNode(String data)