Chapter 24. DOM Reference
The Document
Object Model (DOM) is
a language- and platform-independent object framework for
manipulating structured documents (see Chapter 18
for additional information). The current W3C recommendation specifies
what is called the Level 2 DOM.
The full Level 2 DOM is designed to support editing of HTML
documents, with several classes and methods specific to HTML document
structures. This larger DOM is built on top of a smaller, but
complete, subset called the Core DOM. Only the Core DOM is required to
support editing of XML documents.
TIP:
Other parts of DOM Level 2 may be useful for specific kinds of XML
processing, particularly the Style, Traversal, and Range modules.
This reference section documents the Levels 1 and 2 Core DOM
objects, using the language-neutral OMG IDL object descriptions.
Included with each IDL description is the language-specific binding
for the
Java programming language. Level
2-only constructs are indicated using the
2 symbol after the given attribute or
method name. TIP:
This chapter is based on the Document Object Model (DOM) Level 2 Core
Specification, which was released on November 13, 2000. The latest
version of this recommendation, along with any errata that have been
reported, is available on the W3C DOM Activity's web
site (http://www.w3.org/DOM/DOMTR).
The
DOM
structures a document as a hierarchy
of Node objects. The Node
interface is the base interface for every member of a DOM document
tree. It exposes attributes common to every type of document object
and provides a few simple methods to retrieve type-specific
information without resorting to downcasting. This interface also
exposes all methods used to query, insert, and remove objects from
the document hierarchy. The Node interface makes
it easier to build general- purpose tree-manipulation routines that
are not dependent on specific-document element types. CharacterData (continued) | |
Methods
The following methods are defined for
CharacterData:
replaceData: offset, count, arg | |
This
replaces a substring within the data attribute
with another string value arg, using the specifed
offset and count parameters.
Arguments
- offset: long
-
The offset of the beginning of the replacement region.
- count: long
-
The number of characters to replace. If offset +
count is >= the
length attribute, everything beyond the
offset character position is replaced.
- arg: DOMString
-
The replacement string.
The replaceData operation is the equivalent of the
following code fragment:
cdNode.deleteData(offset, count);
cdNode.insertData(offset, arg);
Exceptions
- INDEX_SIZE_ERR
-
Raised if the offset parameter is not a valid,
zero-based index into the data
DOMString.
- NO_MODIFICATION_ALLOWED_ERR
-
Raised if the node is read-only.
Java binding
public void replaceData(long offset, long count,
String arg) throws DOMException;
Java example
// Create a new Text object and reference the CharacterData interface
CharacterData ndCD = (CharacterData)doc.createTextNode("The truth is
not out there.");
// replace the truth
String strFind = "truth";
String strReplace = "dog";
ndCD.replaceData(ndCD.getData().indexOf(strFind), strFind.length( ),
strReplace);
System.out.println(ndCD.getData( ));
Methods
The following methods are defined for the
Document object:
This function creates an
Attr object with the given name.
Attr nodes construct complex element attributes
that can include EntityReference objects and text
data.
Argument
- name: DOMString
-
The name of the XML attribute.
Return value
The new Attr object.
Exception
- INVALID_CHARACTER_ERR
-
Indicates that the name you passed to createAttribute(
) doesn't conform to a valid XML name. See
Chapter 2 for the XML restrictions on name
construction.
Java binding
public Attr createAttribute(String name) throws DOMException;
Java example
// Create an entity reference
EntityReference er = doc.createEntityReference("name_entity");
// must create an Attribute object to include an explicit
// entity reference
Attr attr = doc.createAttribute("name");
// append the entity reference
attr.appendChild(er);
createAttributeNS: namespaceURI, qualifiedName2 | |
This method serves the same purpose as the
createAttribute method, but includes support for
XML namespaces. See Chapter 4 for more information
about namespaces.
Arguments
- namespaceURI: DOMString
-
The URI associated with the namespace prefix in the
qualifiedName parameter.
- qualifiedName: DOMString
-
The name of the attribute to instantiate; includes the namespace
prefix associated with the namespace URI given in the
namespaceURI parameter.
Return value
The new Attr object is returned with the following
attribute values:
Attribute
|
Value
|
Node.nodeName
|
The complete, fully qualified name given in the
qualifiedName parameter
|
Node.namespaceURI
|
The given namespace URI
|
Node.prefix
|
The namespace prefix, which is parsed from the
qualifiedName parameter
|
Node.localName
|
The local part of the qualified name, located to the right of the
: character
|
Attr.name
|
The qualifiedName
|
Exceptions
- INVALID_CHARACTER_ERR
-
Indicates that the name passed to createAttributeNS(
) doesn't conform to a valid XML name. See
Chapter 2 for the XML restrictions on name
construction.
- NAMESPACE_ERR
-
Raised if the qualifiedName is malformed or has a
prefix but no namespaceURI, or if the reserved
xml namespace prefix was used incorrectly.
Java binding
public Attr createAttributeNS(String namespaceURI, String qualifiedName)
throws DOMException;
This
returns a new Comment node containing the
specified string. See the Comment object reference earlier in
this chapter for special restrictions that apply to the contents of
Comment nodes.
Argument
- data: DOMString
-
The comment text.
Comment text restriction
The XML specification indicates that the --
characters must not appear in the comment text for compatibility
reasons. Despite this warning, some DOM implementations
don't flag comments containing double hyphens as
syntax errors.
Java binding
public Comment createComment(String data);
Java example
// Create a timestamp comment
StringBuffer sb = new StringBuffer( );
Date dtNow = new Date( );
sb.append("\tModified " + dtNow.toString( ) + '\n');
Comment cmt = doc.createComment(sb.toString( ));
createDocumentFragment( ) | |
This returns an empty
DocumentFragment object. See the DocumentFragment reference later in this
chapter for a discussion of a document fragment's
uses and limitations.
Java binding
public DocumentFragment createDocumentFragment( );
This
creates a new, empty Element node for use within
the parent document. The element name is given as an argument to the
method. The resulting Element node belongs to the
parent Document object, but is not part of the
document element hierarchy. See Node later in this
chapter for more information about how the document hierarchy
manipulation methods are used.
Argument
- tagName: DOMString
-
The XML name used to create the new Element node.
This name is assigned to the nodeName attribute of
the resulting Element node.
Return value
The new Element object.
Exception
- INVALID_CHARACTER_ERR
-
Indicates that the name you passed to createElement(
) doesn't conform to a valid XML name. See
Chapter 2 for the XML restrictions on name
construction.
Java binding
public Element createElement(String tagName) throws DOMException;
Java example
// Create the new my_tag Element
Element elOut = doc.createElement("my_tag");
createElementNS: namespaceURI, qualifiedName2 | |
This method serves the same purpose as the
createElement method, but includes support for XML
namespaces. See Chapter 4 for more information
about namespaces.
Arguments
- namespaceURI: DOMString
-
The URI associated with the namespace prefix in the
qualifiedName parameter.
- qualifiedName: DOMString
-
The name of the element to instantiate, including the namespace
prefix associated with the namespace URI given in the
namespaceURI parameter.
Return value
The new Element object is returned with the
following attribute values:
Attribute
|
Value
|
Node.nodeName
|
The complete, fully qualified name given in the
qualifiedName parameter
|
Node.namespaceURI
|
The given namespace URI
|
Node.prefix
|
The namespace prefix, which is parsed from the
qualifiedName parameter
|
Node.localName
|
The local part of the qualified name, located to the right of the
: character
|
Element.tagName
|
The full element tag name, which is the same as the
qualifiedName
|
Exceptions
- INVALID_CHARACTER_ERR
-
Indicates that the name you passed to createElementNS(
) doesn't conform to a valid XML name. See
Chapter 2 for the XML restrictions on name
construction.
- NAMESPACE_ERR
-
Raised if the qualifiedName is malformed, has a
prefix but no namespaceURI, or if the reserved
xml namespace prefix was used incorrectly.
Java binding
public Element createElementNS(String namespaceURI,
String qualifiedName)
throws DOMException;
createEntityReference: name | |
This creates an
EntityReference object.
Argument
- name: DOMString
-
The name of the XML entity to be referenced. The name must match an
XML entity declaration that is valid in the current document.
Exceptions
- INVALID_CHARACTER_ERR
-
Indicates that the name you passed to createEntityReference(
) doesn't conform to a valid XML name. See
Chapter 2 for the XML restrictions on name
construction.
- NOT_SUPPORTED_ERR
-
Generated if you attempted to create an entity reference using an
HTML document.
Java binding
public EntityReference createEntityReference(String name)
throws DOMException;
Java example
// Create an entity reference
EntityReference er = doc.createEntityReference("name_entity");
importNode: importedNode, deep2 | |
This
method's name is somewhat deceptive. It creates a
copy of a Node object from another document that
can be inserted within the current document's node
hierarchy. Specifics of this copy operation vary, depending on the
type of copied node.
Node type
|
Result
|
Effect of deep flag
|
ATTRIBUTE_NODE
|
Copies the source attribute and all its children. The
ownerElement attribute is set to
null, and the specified flag is
set to true.
|
None.
|
DOCUMENT_FRAGMENT_NODE
|
Creates an empty DocumentFragment node.
|
Fully copies the children of the source
DocumentFragment node.
|
DOCUMENT_NODE
|
Cannot be imported.
|
N/A.
|
DOCUMENT_TYPE_NODE
|
Cannot be imported.
|
N/A.
|
ELEMENT_NODE
|
Copies the attribute nodes with the specified flag
set to the new element.
|
Recursively copies all the source element's children.
|
ENTITY_NODE
|
Copies the publicId, systemId,
and notationName attributes.
|
Recursively copies all of the Entity
node's children.
|
ENTITY_REFERENCE_NODE
|
Copies only the EntityReference node. Its value,
if any, is taken from the DTD of the document doing the import.
|
None.
|
NOTATION_NODE
|
Imports the notation node, but since in Level 2
the DocumentType interface is read-only, it cannot
be included in the target document.
|
None.
|
PROCESSING_INSTRUCTION_ NODE
|
Copies the target and data
values.
|
None.
|
TEXT_NODE,
CDATA_SECTION_NODE, COMMENT_NODE
|
Copies the data and length
attributes.
|
None.
|
The new (copied) node object is returned based on the arguments.
Arguments
- importedNode: Node
-
The node duplicated for use in the current document hierarchy.
- deep: boolean
-
Whether to copy the single node given or the entire subtree of its
children. For details, see the previous table.
Exception
- NOT_SUPPORTED_ERR
-
Thrown if an attempt is made to import an unsupported Node type, such
as a Document node.
Java binding
public Node importNode(Node importedNode, boolean deep)
throws DOMException;
Methods
The following methods are defined for this object:
Returns the attribute specified by the
name parameter as a DOMString.
See the getAttributeNode:name for a
complete explanation of how an attribute value is determined. This
returns an empty string if no attribute is set and if no default
attribute value was specified in the DTD.
Java binding
public String getAttribute(String name);
Java example
// Check for the name attribute
Element elem = doc.getDocumentElement( );
if (elem.getAttribute("name") == "") {
System.out.println("warning: " + elem.getTagName( ) +
" element: no name attribute");
}
Methods
The following methods are defined for the
NamedNodeMap object:
Inserts the given Node
object into the list, using its nodeName
attribute. Since many DOM node types expose the same, hardcoded value
for this property, storing only one of them in a single
NamedNodeMap is possible. Each subsequent
insertion overwrites the previous node entry. See the nodeName: DOMString topic for a discussion of
these special name values.
This method returns a reference to the Node object
that the new node replaces. If no nodes with the same
nodeName value are currently in the map, this
method returns null.
Argument
- arg: Node
-
The Node object to be stored in the map. The value
of the nodeName property is used as the lookup
key. A node with the same nodeName value as the
new node is replaced with the node referenced by
arg.
Exceptions
- WRONG_DOCUMENT_ERR
-
Raised if a document different than the creator of the target
NamedNodeMap created the arg node.
- NO_MODIFICATION_ALLOWED_ERR
-
Raised if the NamedNodeMap is read-only.
- INUSE_ATTRIBUTE_ERR
-
Raised if the arg node is an
Attr node that is already in use by another
element's attributes map.
Java binding
public Node setNamedItem(Node arg) throws DOMException;
Java example
// Check to see if an ID attribute exists
// in this map, and add it if necessary
if (nnm.getNamedItem("id") == null) {
// get the document
Document doc = elem.getOwnerDocument( );
// create a new attribute Node
Attr attrID = doc.createAttribute("id");
// set the attribute value
attrID.appendChild(doc.createTextNode(makeUniqueID(elem)));
// ... and add it to the NamedNodeMap
nnm.setNamedItem(attrID);
}
The Node interface is the base interface for every
member of a DOM document tree. It exposes attributes common to every
type of document object and provides simple methods to retrieve
type-specific information without resorting to downcasting. For
instance, the attributes list provides access to
the Element object's attributes,
but it would have no meaning for a
ProcessingInstruction node. (Extracting
pseudoattributes from a processing instruction requires your
application to parse the contents of the processing instruction.)
This interface also exposes all methods for querying, inserting, and
removing objects from the document hierarchy. The
Node interface makes it easier to build
general-purpose tree-manipulation routines that are not dependent on
specific document element types.
Attributes
The following attributes provide information
about where the Node object is located within the
document tree. These attributes are read-only. Additional methods
allow the insertion and removal of nodes from the document tree.
Intended to represent the underlying
DOM object's name. Depending on the object type,
this attribute may map to another attribute of the object or a
constant string:
Java binding
public String getNodeName( );
// Print the document root tag name
Node ndDoc = (Node)doc.getDocumentElement( );
System.out.println("Document root element type: " + ndDoc.getNodeName( ));
Contains a value that indicates the
true type of the object referenced through the
Node interface. The following table shows this
attribute's possible values, along with the actual
object types they represent:
The parent-child and sibling relationships between nodes can be
visualized as two doubly linked lists. One list links parents to
children, while the other links nodes that exist at the same level.
Java binding
public short getNodeType( );
Java example
// Check to see if a node is an Element type node
public boolean isElement(Node nd) {
return nd.getNodeType( ) == Node.ELEMENT_NODE;
}
Intended to provide a reasonable
string value for the underlying DOM object. Depending on the
nodeType, this property may be read-only, read/
write, or null.
Exceptions
- NO_MODIFICATION_ALLOWED_ERR
-
Indicates the nodeValue attribute is read-only for
this DOM object type.
- DOMSTRING_SIZE_ERR
-
This exception is raised if the value that would be returned is too
large to be contained by a DOMString type in the
given implementation.
Java bindings
public String getNodeValue( ) throws DOMException;
public void setNodeValue(String nodeValue) throws DOMException;
Java example
// If this node is a text node, make the value lowercase
if (nd.getNodeType( ) == Node.TEXT_NODE) {
// make it lowercase
nd.setNodeValue(nd.getNodeValue().toLowerCase( ));
}
Methods
The following methods are defined for
Node interface objects:
insertBefore: newchild, refchild | |
Inserts the Node object
newchild into the child list of the parent node
that invokes it. The refchild parameter allows you
to specify where to insert the new node in the list. If
refchild is null, the new node
is inserted at the end of the child list. (This behavior is the same
as appendChild.) If it is not
null, the new node is inserted into the list in
front of the specified node. If the newchild node
is already part of the document tree, it is unlinked before it is
inserted in its new position. Also, if the
newchild node references a
DocumentFragment object, each of its children are
inserted, in order, before the refchild node. A
reference to the newchild node is returned.
Arguments
- newchild: Node
-
The new node to insert.
- refchild: Node
-
The node that follows the new node in the child list, or
null, if the new node is inserted at the end of
the child list.
Exceptions
- HIERARCHY_REQUEST_ERR
-
Raised if the insert operation would violate at least one document
structure rule. For instance, the node doesn't allow
children or doesn't allow children of the
newchild node type. This exception is also raised
if the operation creates a circular reference (i.e., it tries to
insert a node's parent as a node's
child).
- WRONG_DOCUMENT_ERR
-
Raised if the newchild node was created in a
document different than that of the new parent node.
- NO_MODIFICATION_ALLOWED_ERR
-
Raised if the new parent node is read-only.
- NOT_FOUND_ERR
-
Raised if the node pointed to by refchild is not a
child of the node performing the insert.
Java binding
public Node insertBefore(Node newChild, Node refChild)
throws DOMException;
Java example
// Insert a new node at the head of the child list of a parent node
ndParent.insertBefore(ndNew, ndParent.getFirstChild( ));
isSupported: feature, version2 | |
Checks
to see if a particular DOM feature is available for this
implementation. For more information about the feature names, see the
hasFeature: feature, version method of the DOMImplementation object earlier in this
chapter. This method returns true if the feature is available,
false if it is not.
Arguments
- feature: DOMString
-
The name of the feature to test for. See detail of the hasFeature: feature, version method of the DOMImplementation object for a list of this
parameter's valid values.
- version: DOMString
-
The version number of the feature to test. For DOM Level 2, Version
1, this string should be 2.0. If the version is not specified, this
method tests for any version of the feature.
Java binding
public boolean supports(String feature, String version);
 |  |  | 23.4. TrAX |  | 24.2. Object Reference |
Copyright © 2002 O'Reilly & Associates. All rights reserved.
|