the document object model xml dom. the javascript object hierarchy
TRANSCRIPT
The Document Object Model
XML DOM
The JavaScript Object Hierarchy
Referring to (DOM) objects
window.resizeTo(300,300);
document.write("<H4>" + navigator.userAgent + "</H4>");
parent.frame[1].location.replace(“someFile.html");
d = new Date();document.write(d.toGMTString());
JavaScript Document Object Model
• Document methods– write(string)
document.write(“<H1>Home</H1>”);• inserts content in <html> element
• Document attributes– alinkColor, linkColor, vlinkColor – bgColor, fgColor
JavaScript Document Object Model
• Objects relating to (sets of) elements in the Document content– images [ ]– forms [ ]– links[ ]– anchors [ ]– applets [ ]
What is the XML DOM?
• API for manipulating XML
• applies to all well-formed XML structures
• Defined and maintained by W3C– DOM Level 2: November 13th 2000– DOM Level 3 Working Draft: January 14th 2002
• developers use specific language bindings of DOM standard– e.g. JavaScript binding of XML DOM, Java DOM
classes (JAXP, JDOM)
The DOM API Core
• defines interfaces to all document content types– attributes and methods
• generic Node interface– provides general methods and attributes for any
XML Node type
• specific node type interfaces– inherit from Node interface but provide specific
functionality
Document
Document fragment
DocumentType
Processing Instruction
Character Data
Element
Attr
Entity Reference
Entity
Notation
Comment
Text
CDATA section
DOMImplementation
NamedNodeMap
Node list
DOM Exception
Node
UML model of XML DOM core classes and interfaces
generic generic
specific Node types
ATTRIBUTE_NODE
CDATA_SECTION_NODE
COMMENT_NODE
DOCUMENT_FRAGMENT_NODE
DOCUMENT_NODE
DOCUMENT_TYPE_NODE
ELEMENT_NODE
TEXT_NODE
ENTITY_NODE
ENTITY_REFERENCE_NODE
NOTATION_NODE
PROCESSING_INSTRUCTION_NODE
XML DOM Node Types
the Node interfaceAttributes (most of these are read-only):
nodeName DOMString
nodeValue DOMString
type unsigned short
parentNode Node, childNodes NodeList
firstChild Node, lastChild Node
previousSibling Node, nextSibling Node
attributes NamedNodeMap
ownerDocument Document
namespaceURI, Prefix, localName DOMString
the Node interfaceMethods:
Boolean hasAttributes ( )
Boolean hasChildNodes ( )
Node InsertBefore (Node newChild, Node refChild) Node replaceChild (Node newChild, Node oldChild)
Node removeChild (Node oldChild)
Node appendChild (Node newChild)
Node cloneNode (Boolean Deep)
Boolean isSupported (DOMString Feature,DOMString version )
Void normalize ( )
the NodeList interfaceAttributes:
Long integer length
Methods:
Node item (integer index)
Example of use:
for (i = 0; i < theList.length; i++)
doSomethingWith (theList.item (i));
specific node type interfaces
• structural nodes– DocumentType, ProcessingInstruction, Notation,
Entity– provide mostly read only information about
structural or document-handling instructions
• content nodes– Document, Element, Attr, Text etc.– provide manipulable interface to the data content
of the XML
The Document Structure
Document
Element
Text
Attr
Element
the Document interfaceAttributes (all of these are read-only):
docType DocumentType
implementation DOMImplementation
documentElement Element
Example of Use:
root = theDocument.documentElement;
//the root now contains the entire body of the parsed document
the Document interfaceMethods:
Attr createAttribute (DOMString name)
Element createElement (DOMString tagName)
Text createTextNode (DOMString textData)
can also create comments, CDATA, etc...
Element getElementById(DOMString id)
NodeList getElementsByTagName(DOMString tagName)
Example of use:
theContents = doc.getElementsByTagName (“item”);
// gets all “item” elements in the document
the Element interfaceAttributes (read-only):
tagName DOMString
Methods:
DOMString getAttribute (DOMString name)
Attr getAttributeNode (DOMString name)
NodeList getElementsByTagName(DOMString tagName)
Boolean hasAttribute (DOMString name)
Void removeAttribute (DOMString name)
Attr removeAttributeNode (DOMString name)
Void setAttribute (DOMString name)
Attr setAttributeNode (Attr newAttribute)
the Element interfaceMethods:
Attr createAttribute (DOMString name)
Element createElement (DOMString tagName)
Text createTextNode (DOMString textData)
can also create comments, CDATA, etc...
Element getElementById(DOMString id)
NodeList getElementsByTagName(DOMString tagName)
Example of use:
theContents = doc.getElementsByTagName (“item”);
// gets all “item” elements in the document
the Attr interface
Attributes (all read-only except value):
name DOMString
ownerElement Element
specified Boolean
value DOMString
Example of use:
theColour = gandalf.getAttributeNode ("colour");theColour.value = "Grey";
balrog (gandalf);theColour.value = "White";
The JavaScript binding of DOM
client-side DOM manipulation• loading XML data
– MSXML ActiveXObject in IE6– get XML data file from a URL
• use JavaScript binding to manipulate and present data– implements XML DOM interface– also HTML-specific features
• innerHTML property
• post data to server for serialisation
• used by AJAX
XML DOM in JavaScript <FORM><TABLE border = "2" style = "font-size:large;"><TR><TD>Hugo First</TD><TD><INPUT TYPE = "CHECKBOX" NAME = "present" ></TD></TR><TR><TD>Sue Pladle</TD><TD><INPUT TYPE = "CHECKBOX" NAME = "present" ></TD></TR>... </TABLE><INPUT TYPE = "BUTTON" VALUE = "ABSENT”
ONCLICK = "hide (true);"><INPUT TYPE = "BUTTON" VALUE = "PRESENT”
ONCLICK = "hide (false);"><INPUT TYPE = "BUTTON" VALUE = "ALL”
ONCLICK = "showall ();"></FORM>
XML DOM in JavaScriptfunction hide (flag) {
var rows = document.getElementsByTagName("tr");var boxes = document.getElementsByName("present");var count = 0;for (var i = 0; i < rows.length; i++) {
if (boxes[i].checked == flag) {rows [i].style.display = "none";
} else {count++;rows[i].style.display = "block";
}}
var mesg = document.getElementById("mesg");mesg.innerHTML = ("Showing " + count + " out of "
+ rows.length + "students");}
XML DOM in JavaScriptfunction showall () {
var rows = document.getElementsByTagName("tr");for (var i = 0; i < rows.length; i++)
rows[i].style.display = "block";mesg.innerHTML = ("Showing " + rows.length
+ " out of " + rows.length);}
<SCRIPT LANGUAGE="JavaScript">var rows = document.getElementsByTagName("tr");document.write("<P ID=\"mesg\">");document.write("Showing " + rows.length
+ " out of " + rows.length);document.write("</P>");
</SCRIPT>
The Java DOM binding
JAXP classes
XML source Java Program
original data
modified data
load, modify, serialise
Java and XML
• javax.xml.parser package– JAXP - Java API for XML Processing
• provides parser classes for DOM and SAX parsing of XML
• org.w3c.dom package contains essentially the Java binding of the XML DOM
• org.xml.sax package contains SAX API
• javax.xml.transform– XSLT API (part of JAXP 1.1)
The Java binding of DOM
XMLdata
DocumentBuilder
DocumentBuilderFactory
DOM
The Java binding of DOM
• generic and specific Node types implemented as Java classes– org.w3c.dom.Document;– org.w3c.dom.Element;
– org.w3c.dom.Attr; … etc.
• methods and attributes correspond to the DOM specification– typing is more of an issue than in JavaScript
• JDOM – www.jdom.org – Java oriented access for XML documents
simple example<?xml version = "1.0"?>
<!-- myIntro.xml --><!-- a simple introduction to Java DOM processing -->
<!DOCTYPE myMessage [ <!ELEMENT myMessage ( message )> <!ELEMENT message ( #PCDATA )>]>
<myMessage> <message>This text will be replaced</message></myMessage>
simple example
// ReplaceText class// Reads an XML file and replaces a text node.
// first import the necessary classes
import java.io.*;import org.w3c.dom.*;import javax.xml.parsers.*;import org.apache.crimson.tree.XmlDocument;import org.xml.sax.*;
simple examplepublic class ReplaceText { private Document document;
public ReplaceText() { try {
// obtain the default parser DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// set the parser to validating factory.setValidating( true ); DocumentBuilder builder = factory.newDocumentBuilder();// builder can now be used to construct a DOM tree
simple example// obtain document object from XML documentdocument = builder.parse( new File( "myIntro.xml" ) );
// now we can do the standard DOM stuff// first, we get the root node
Node root = document.getDocumentElement();
if ( root.getNodeType() == Node.ELEMENT_NODE ) { Element myMessageNode = ( Element ) root;// make a NodeList of all the message elements NodeList messageNodes = myMessageNode.getElementsByTagName( "message" );// get the first message element in the list if ( messageNodes.getLength() != 0 ) { Node message = messageNodes.item( 0 );
simple example // create a text node Text newText =
document.createTextNode(”Text has been replaced!");
// get the old text node, note the explicit typecast Text oldText = ( Text ) message.getChildNodes().item( 0 );
// replace the text message.replaceChild( newText, oldText ); }}
/** the text content of the message element has been* replaced*/
simple example// now write out to an XML file and specify the error-handling behaviour ( (XmlDocument) document).write(
new FileOutputStream(”newIntro.xml" ) ); } catch ( SAXParseException spe ) { System.err.println( "Parse error: " + spe.getMessage() ); System.exit( 1 ); } catch ( SAXException se ) { se.printStackTrace(); } catch ( FileNotFoundException fne ) { System.err.println( "File \'myIntro.xml\' not found. " ); System.exit( 1 ); } catch ( Exception e ) { e.printStackTrace(); }}