430 likes | 548 Views
SE 5145 – eXtensible Markup Language ( XML ). DOM ( Document Object Model ) (Part I). 2011-12/Spring, Bahçeşehir University , Istanbul. 4h Assignment: DOM implementation of XML Resume. Implement DOM to your Resume.
E N D
SE 5145 – eXtensibleMarkup Language (XML) DOM (Document Object Model) (Part I) 2011-12/Spring, Bahçeşehir University, Istanbul
4h Assignment: DOM implementation of XML Resume Implement DOM to your Resume. Required: There must exist a Checkbox containing the labels "Technical" and "Management". Upon checking the label(s), relevant sections of your Resume must be highligted with different colors. Optional: A "Show experience duration" button should calculate the sum of check-ed experiences. You can write the implementation by using one of the following ways; a) Javascript (Due April 27) or b) Java, C#, or any other language you prefer (Due May11) Notes: 1. A sample Javascript based DOM implementation is displayed on the next slide. Relevant files will also be sent to you. 2. Details of the assignment was already discussed at the last lecture. If you did not attend it, please ask the details to your classmates, not to me since nowadays I' m not available to reply individual emails.
Sample DOM Implementation • Inspect the files: • JoesCafe.html • JoesCafeCode.js
DOM (Document Object Model) • Q:How to provide uniform access to structured documents in diverse applications (parsers, browsers, editors, databases)? • A: Use an XML API (DOM or SAX)
XML APIs • XML processors make the structure and contents of XML documents available to applications through APIs • Event-based APIs • notify application through parsing events • e.g., the SAX call-back interfaces • Object-model (or tree) based APIs • provide a full parse tree • e.g, DOM, W3C Recommendation • more convenient, but may require too much resources with the largest documents • Major parsers support both SAX and DOM
DOM: What is it? • W3C standard adopted in 1998 • An object-basedAPI for XML and HTML documents • Developedto support "dynamic HTML" • Provide a standard tree interface to document structure across browsers, for use in JavaScript • Provides a standardized way of buildingdocuments, navigatingtheir structure, adding, modifyingor deleting elements and content using programmatic techniques (by programs and scripts). • Provides a foundation for developing, querying, filtering,transformation, rendering etc. applications on top of DOM implementations
DOM: What is it? • Platform-, browser- and language-neutral • Programming-language specific mappings for JavaScript, Java as partof the specification • Implementations in other languages: C++, Python, C#, ... • In contrast to “Serial Access XML” (for SAX) could think as “Directly Obtainable in Memory” (for DOM).
SAX vs. DOM • DOM reads the entire XML document into memory and stores it as a tree data structure • SAX reads the XML document and sends an event for each element that it encounters • Consequences: • DOM provides “random access” into the XML document • SAX provides only sequential access to the XML document • DOM is slow and requires huge amounts of memory, so it cannot be used for large XML documents • SAX is fast and requires very little memory, so it can be used for huge documents (or large numbers of documents) • This makes SAX much more popular for web sites • Some DOM implementations have methods for changing the XML document in memory; SAX implementations do not
Overview of W3C DOM Specification Secondone in the “XML-family” of recommendations • Different levels of implementation: • Level 1 (W3CRec, Oct. 1998): Flat object model (two features: DOM and HTML) • Level 2 (W3C Rec, Nov. 2000): API structured into multiple modules • Core, XML, HTML, Range, Traversal, ... • Level 3 (W3C Working Draft (January 2002): New and revised modules • new: Load and Save, Validation • revised: Core, Events • in progress, W3C Notes: XPath, Views and Formatting, ...
DOM Features • Core: Represent basic structure of well-formed XMLdocuments • XML: Access entities, notations, ... • Events: Communicate user interaction and document changes to the application • HTMLEvents, MutationEvents, UIEvents, ... • Range: Select portions of a document • Traversal: Process/Filter nodes in sequence • Views: Access alternative representations of a document • StyleSheet/CSS: Represent of style sheets • HTML: Represent HTML documents • LS, LS-Async: Load and Save
DOM Tree & Nodes Text nodes are seperate nodes in the tree, not considered to be parts of the tags
DOM structure model • Based on O-O concepts: • methods (to access or change object’s state) • interfaces (declaration of a set of methods) • objects (encapsulation of data and methods) • Roughly similar to the XSLT/XPath data model (to be discussed later) a parse tree • Tree-like structure implied by the abstract relationships defined by the programming interfaces; Does not necessarily reflect data structures used by an implementation (but probably does)
Structure of DOM Level 1 I: DOM Core Interfaces • Fundamental interfaces • basic interfaces to structured documents • Extended interfaces • XML specific: CDATASection, DocumentType, Notation, Entity, EntityReference, ProcessingInstruction II: DOM HTML Interfaces • more convenient to access HTML documents • (we ignore these)
DOM Level 2 • Level 1: basic representation and manipulation of document structure and content (No access to the contents of a DTD) • DOM Level 2 adds • support for namespaces • accessing elements by ID attribute values • optional features • interfaces to document views and style sheets • an event model (for, say, user actions on elements) • methods for traversing the document tree and manipulating regions of document (e.g., selected by the user of an editor) • Loading and writing of docs not specified (-> Level 3)
Structure of the DOM tree • The DOM tree is composed of Node objects • Node is an interface • Some of the more important subinterfaces are Element, Attr, and Text • An Element node may have children • Attr and Text nodes are leaves • Additional types are Document, ProcessingInstruction, Comment, Entity, CDATASection and several others • Hence, the DOM tree is composed entirely of Node objects, but the Node objects can be downcast into more specific types as needed
<invoice> <invoicepage form="00" type="estimatedbill"> <addressee> <addressdata> <name>Leila Laskuprintti</name> <address> <streetaddress>Pyynpolku 1 </streetaddress> <postoffice>70460 KUOPIO </postoffice> </address> </addressdata> </addressee> ... invoice form="00" type="estimatedbill" invoicepage addressee addressdata Document name address Element Leila Laskuprintti streetaddress postoffice Text NamedNodeMap Pyynpolku 1 70460 KUOPIO DOM structure model
Core Interfaces: Node & its variants Node Document DocumentFragment Element Attr CharacterData “Extended interfaces” Comment Text CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
Node getNodeType getNodeValue getOwnerDocument getParentNode hasChildNodes getChildNodes getFirstChild getLastChild getPreviousSibling getNextSibling hasAttributes getAttributes appendChild(newChild) insertBefore(newChild,refChild) replaceChild(newChild,oldChild) removeChild(oldChild) Document Element Text NamedNodeMap DOM interfaces: Node invoice form="00" type="estimatedbill" invoicepage addressee addressdata name address Leila Laskuprintti streetaddress postoffice Pyynpolku 1 70460 KUOPIO
Operations on Nodes, I • The results returned by getNodeName(), getNodeValue(), getNodeType() and getAttributes() depend on the subtype of the node, as follows: • Element Text AttrgetNodeName() getNodeValue()getNodeType()getAttributes() tag namenullELEMENT_NODENamedNodeMap "#text"text contentsTEXT_NODEnull name of attributevalue of attributeATTRIBUTE_NODEnull
Distinguishing Node types • Here’s an easy way to tell what kind of a node you are dealing with: • switch(node.getNodeType()) { • case Node.ELEMENT_NODE: • Element element = (Element)node;...;break; • case Node.TEXT_NODE: • Text text = (Text)node;...break; • case Node.ATTRIBUTE_NODE: • Attr attr = (Attr)node;...break; • default: ... • }
Operations on Nodes, II • Tree-walking operations that return a Node: • getParentNode() • getFirstChild() • getNextSibling() • getPreviousSibling() • getLastChild() • Tests that return aboolean: • hasAttributes() • hasChildNodes()
Document Element Text NamedNodeMap Node DOM interfaces: Document Document getDocumentElement createAttribute(name) createElement(tagName) createTextNode(data) getDocType() getElementById(IdVal) invoice form="00" type="estimatedbill" invoicepage addressee addressdata name address Leila Laskuprintti streetaddress postoffice Pyynpolku 1 70460 KUOPIO
Document Element Text NamedNodeMap Node DOM interfaces: Element Element getTagName getAttributeNode(name) setAttributeNode(attr) removeAttribute(name) getElementsByTagName(name) hasAttribute(name) invoice form="00" type="estimatedbill" invoicepage addressee addressdata name address Leila Laskuprintti streetaddress postoffice Pyynpolku 1 70460 KUOPIO
Operations for Elements • String getTagName() • Returns the name of the tag • boolean hasAttribute(String name) • Returns true if this Element has the named attribute • String getAttribute(String name) • Returns the (String) value of the named attribute • boolean hasAttributes() • Returns true if this Element has any attributes • This method is actually inherited from Node • Returns false if it is applied to a Node that isn’t an Element • NamedNodeMap getAttributes() • Returns a NamedNodeMap of all the Element’s attributes • This method is actually inherited from Node • Returns null if it is applied to a Node that isn’t an Element
Operations on Texts • Text is a subinterface of CharacterData which, in turn, is a subinterface of Node • In addition to inheriting the Node methods, it inherits these methods (among others) from CharacterData: • public String getData() throws DOMException • Returns the text contents of this Text node • public int getLength() • Returns the number of Unicode characters in the text • public String substringData(int offset, int count) throws DOMException • Returns a substring of the text contents • Text also declares some methods • public String getWholeText() • Returns a concatenation of all logically adjacent text nodes
Operations on Attrs • String getName() • Returns the name of this attribute. • Element getOwnerElement() • Returns the Element node this attribute is attached to, or null if this attribute is not in use • boolean getSpecified() • Returns true if this attribute was explicitly given a value in the original document • String getValue() • Returns the value of the attribute as a String
Object Creation in DOM • Each DOM object X lives in the context of aDocument: X.getOwnerDocument() • Objects implementing interface X are created by factory methods D.createX(…) ,where D is aDocumentobject. E.g: • createElement("A"), createAttribute("href"), createTextNode("Hello!") • Creation and persistent saving of Documents left to be specified by implementations
Accessing properties of aNode • Node.getNodeName() • for an Element = getTagName() • for an Attr: the name of the attribute • for Text = "#text" etc • Node.getNodeValue() • content of a text node, value of attribute, …; null for an Element (!!) (in XSLT/Xpath: the full textual content) • Node.getNodeType():numeric constants (1, 2, 3, …, 12) forELEMENT_NODE, ATTRIBUTE_NODE,TEXT_NODE, …, NOTATION_NODE
Content and element manipulation • ManipulatingCharacterDataD: • D.substringData(offset, count) • D.appendData(string) • D.insertData(offset, string) • D.deleteData(offset, count) • D.replaceData(offset, count, string)(= delete + insert) • Accessing attributes of anElement object E: • E.getAttribute(name) • E.setAttribute(name, value) • E.removeAttribute(name)
Exercises – JAVA SCRIPT • Discovering Document Information • Creating New Document Content
Exc. 3: Creating New Document Content • Now, try: • Adding more <BusinessCard> s • Modifying Tags (change, remove, etc)