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.
| Attr |
The Attr interface represents the value assigned to an attribute of an XML element. Since the attributes NamedNodeList attribute of the Element interface is the only access to Attr objects within the DOM, the parentNode, previousSibling, and nextSibling attributes always return null. Although the Attr interface inherits the Node base interface, many basic Node methods are not applicable.
An XML element can acquire an attribute in several ways. An element has an attribute value if:
The XML document explicitly provides an attribute value.
The document DTD specifies a default attribute value.
An attribute is added programmatically using the setAttribute( ) or setAttributeNode( ) methods of the Element interface.
Though an Attr node is not officially part of the DOM document tree, it can be the parent of a value subtree. An Attr object can have EntityReference objects as children. The value attribute provides the expanded DOMString representation of this attribute. To determine if any entity replacements were made, it is necessary to check the Attr node for child nodes.
//Get the element's size attribute as an Attr object
Attr attrName = elem.getAttributeNode("size");
The following attributes are defined for the Attr object:
name: DOMString
The name of the attribute. Read-only.
Java binding
Public String getName( );Java example
// Dump element attribute names Attr attr; for (int i = 0; i < elem.getAttributes().getLength( ); i++) { // temporarily alias the attribute attr = (Attr)elem.getAttributes( ).item(i); System.out.println(attr.getName( )); }
specified: boolean
This indicates whether this attribute was explicitly set in the XML source for the parent element or it is a default value specified in the DTD. Read-only.
Java binding
public boolean getSpecified( );Java example
// Dump element attribute names for (int i = 0; i < elem.getAttributes().getLength( ); i++) { // temporarily alias the attribute attr = (Attr)elem.getAttributes( ).item(i); // only show attributes that were explicitly included in the XML //source file // (i.e. ignore default attributes from the DTD.) if (attr.getSpecified( )) { System.out.println(attr.getName( )); } }
value: DOMString
This attribute provides a simple way to set and retreive the Attr object's text value. When used to get the text value, the attribute includes the expanded value of any general entity references. When used to set the value, it creates a child Text node that contains the string value. Attempting to set the value on a read-only node raises the NO_MODIFICATION_ALLOWED_ERR DOM exception.
Java bindings
public String getValue( ); public void setValue(String value);Java example
// Make all attribute values lowercase Attr attr; for (int i = 0; i < elem.getAttributes().getLength( ); i++) { attr = (Attr)elem.getAttributes( ).item(i); attr.setValue(attr.getValue().toLowerCase( )); }
| CDATASection |
The CDATASection interface contains the unparsed, unescaped data contained within CDATA blocks in an XML document. Though this interface inherits the Text interface, adjacent CDATASection blocks are not merged by the normalize( ) method of the Element interface.
// Open an XML source file
try {
FileInputStream fis = new FileInputStream("phone_list.xml");
StringBuffer sb = new StringBuffer( );
// read the XML source file into memory
int ch;
while ((ch = fis.read( )) != -1) {
sb.append((char)ch);
}
// now, create a CDATASection object to contain it within
// an element of our document using the CDATA facility
CDATASection ndCDATA = doc.createCDATASection(sb.toString( ));
} catch (IOException e) {
...
CDATASection is a pure subclass of the Text interface and has no attributes or methods of its own. See the Text interface section of this chapter for a list of applicable methods for accessing character data in nodes of this type.
| CharacterData |
The CharacterData interface is completely abstract, extending the basic Node interface only to support manipulation of character data. Every DOM object type that deals with text data inherits, directly or indirectly, from this interface.
This interface's string-handling facilities are similar to those found in most modern programming languages. Like C/C++ string-processing routines, all CharacterData routines are zero-based.
// Create a new, unattached Text node
Text ndText = doc.createTextNode("The truth is out there.");
// cast it to the CharacterData interface
CharacterData ndCD = (CharacterData)ndText;
The following attributes are defined for CharacterData:
data: DOMString
This attribute allows access to the "raw" data of the CharacterData node. Though a given DOM implementation cannot arbitrarily limit the amount of character data that can be stored in a CharacterData node, you may need to use the substringData method to retrieve the data in manageable sections because of implementation constraints.
Exceptions
- NO_MODIFICATION_ALLOWED_ERR
- Raised on a write attempt when the data attribute is read-only for this DOM object type.
- DOMSTRING_SIZE_ERR
- Raised if the read value that would be returned is too large to be contained by a DOMString type in the given implementation.
Java bindings
public String getData( ) throws DOMException; public void setData(String data) throws DOMException;Java example
// Quote the CharacterData node contents CharacterData ndCD = (CharacterData)doc.createTextNode("Unquoted text."); ... ndCD.setData('\"' + ndCD.getData( ) + '\"');
length: unsigned long
The size of the DOMString stored in the data attribute. For all methods of this interface that take an index parameter, the valid range for the index is <= index < length. This value can be 0, since having an empty CharacterData node is possible. Read-only.
Java binding
public long getLength( );Java example
// Display the contents of a CharacterData node CharacterData ndCD = (CharacterData)doc.createTextNode("This string has 30 characters."); System.out.println("The string \'" + ndCD.getData( ) + "\' has " + Long.toString(ndCD.getLength( )) + " characters.");
| CharacterData (continued) |
The following methods are defined for CharacterData:
appendData: arg
This method appends contents of the arg parameter to the current contents of the data attribute.
Argument
- arg: DOMString
- The string to append.
Exception
- NO_MODIFICATION_ALLOWED_ERR
- Raised if this node is read-only.
Java binding
public void appendData(String arg) throws DOMException;Java example
// Append to an existing string // Create a new Text object and reference the CharacterData interface CharacterData ndCD = (CharacterData)doc.createTextNode("The truth is "); // flip a coin ndCD.appendData((Math.random( ) < 0.5) ? "out there." : "in here."); System.out.println(ndCD.getData( ));
deleteData: offset, count
This truncates the DOMString in the data attribute. This method removes count characters, starting at the offset position.
Arguments
- offset: unsigned long
- The position in the data attribute to remove count characters.
- count: unsigned long
- The count of characters to remove. If the offset + count is >= the length attribute, the remainder, starting at position offset, is deleted.
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 deleteData(long offset, long count) 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."); // change of heart ndCD.deleteData(12, 4); System.out.println(ndCD.getData( ));
insertData: offsec, arg
This method takes a string, splits the data attribute's current contents at the given offset, then inserts the string from the arg parameter between the two substrings.
Arguments
- offset: unsigned long
- The zero-based offset in the data attribute where the insertion is made.
- arg: DOMString
- The string to be inserted.
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 insertData(long offset, String arg) throws DOMException;Java example
// Insert data into a string boolean fCynical = true; // create a new Text object, and reference the CharacterData interface CharacterData ndCD = (CharacterData)doc.createTextNode("The truth is out there."); ... // check for cynicism if (fCynical) { ndCD.insertData(12, " not"); } System.out.println(ndCD.getData( ));
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( ));
substringData: offset, count
This returns a DOMString that contains a subset of the string stored in the data attribute. The offset and count arguments define the substring. Though the offset argument must represent a valid position within the node data, the end-point of the substring could fall past the end of the data attribute. If this happens, the method returns everything between the offset position and the end of the data string.
Arguments
- offset: unsigned long
- Zero-based, starting offset of the substring to return. A valid offset must be >= 0 and < the length attribute of the node.
- count: unsigned long
- Count of characters to return.
Exceptions
- INDEX_SIZE_ERR
- Raised if the given offset is < 0, >= the length attribute, or if the count parameter is negative.
- DOMSTRING_SIZE_ERR
- Raised if the value that would be returned is too large to be contained by a DOMString type in the given implementation.
Java binding
public String substringData(unsigned long offset, unsigned long count) throws DOMException;Java example
// Get a reference to the CharacterData interface CharacterData ndCD = (CharacterData)doc.createTextNode("The truth is out there."); // we only want the "truth" String strTruth = ndCD.substringData(4, 5); System.out.println("The substring is '" + strTruth + '\'');
| Comment |
This object contains the text of an XML comment (everything between the opening <!-- and closing -->). It inherits from CharacterData.
NOTE: The DOM specification does not require XML parsers to preserve the original document comments after the document is parsed. Some implementations strip comments as part of the parsing process.
// Create a comment
Comment ndComment = doc.createComment("Document was parsed by
DOM utility.");
// and add it to the document
doc.appendChild(ndComment);
| Document |
The Document interface represents an entire, well-formed XML document. Once the Document object is created via the DOMImplementation interface, you can access every aspect of the underlying XML document through the various tree-navigation methods exposed by the Node interface, the parent of the Document interface.
In DOM documents, document elements cannot exist outside of a parent document. For this reason, the Document interface exposes several factory methods used to create new document elements.
The following attributes are defined for the Document object:
doctype: DocumentType
This attribute returns an instance of the DocumentType interface representing the DTD for this document. If no DTD was declared in the document, this property is null. Read-only.
Java binding
public DocumentType getDoctype( );Java example
// Get the parsed DTD information for this document DocumentType docType = docIn.getDoctype( ); if (docType == null) { System.out.println("warning: no DTD provided"); }
documentElement: Element
This attribute points to the single Element node that is the root of the XML document tree. Read-only.
Java binding
public Element getDocumentElement( ); // Identify the root element Element elRoot = docIn.getDocumentElement( ); System.out.println("This is a '" + elRoot.getTagName( ) + "' document.");
implementation: DOMImplementation
This returns a reference to the DOMImplementation that is responsible for this document. It is conceivable (using Adobe's SVG plug-in within Microsoft's Internet Explorer, for example) that a single application might use DOM objects from multiple DOM implementations. Read-only.
Java binding
public DOMImplementation getImplementation( );Java example
// Ensure the support of DOM Level 1 XML DOMImplementation di = doc.getImplementation( ); if (!di.hasFeature("XML", "1.0")) { return false; }
| Document (continued) |
The following methods are defined for the Document object:
createAttribute: name
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.nodeNameThe complete, fully qualified name given in the qualifiedName parameter
Node.namespaceURIThe given namespace URI
Node.prefixThe namespace prefix, which is parsed from the qualifiedName parameter
Node.localNameThe local part of the qualified name, located to the right of the : character
Attr.nameThe 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;
createCDATASection: data
This creates a new CDATASection node that contains the data text. CDATASection nodes contain non-XML text content that would be inconvenient or impractical to quote using the standard XML entities, such as &, <, or >.
Argument
- data: DOMString
- The text contained by the new CDATASection object.
Exception
- NOT_SUPPORTED_ERR
- Occurs if you try to call this method on an HTML document.
Java binding
public CDATASection createCDATASection(String data) throws DOMException;Java example
// Use CDATASection to embed XML characters CDATASection cds = doc.createCDATASection(" <xml_example>This is sample text.</xml_example> ");
createComment: data
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( );
createElement: tagName
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.nodeNameThe complete, fully qualified name given in the qualifiedName parameter
Node.namespaceURIThe given namespace URI
Node.prefixThe namespace prefix, which is parsed from the qualifiedName parameter
Node.localNameThe local part of the qualified name, located to the right of the : character
Element.tagNameThe 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");
createProcessingInstruction: target, data
This creates a new ProcessingInstruction node with the given target name and data values. The processing-instruction target name "xml" (case insensitive) is reserved by the XML working group and can't be used by an application.
Arguments
- target: DOMString
- The target name of the processing instruction. This name identifies the application that will interpret the data portion of the instruction.
- data: DOMString
- The application-specific data for the resulting ProcessingInstruction node.
Exceptions
- INVALID_CHARACTER_ERR
- Indicates that the name you passed in to createProcessing Instruction doesn't conform to a valid XML name. See Chapter 2 for the XML restrictions on name construction.
- NOT_SUPPORTED_ERR
- Generated if you attempt to create a ProcessingInstruction using an HTML document.
Java binding
public ProcessingInstruction createProcessingInstruction(String target, String data) throws DOMException;Java example
// Add the application-specific processing instruction ProcessingInstruction pi = doc.createProcessingInstruction("my_app", "action=\"save\"");
createTextNode: data
This creates a new Text node that contains the given data string.
Argument
- data: DOMString
- The string that will be the contents of the new node.
Java binding
public Text createTextNode(String data);Java example
// Create a new node that contains character data Text txtDesc = doc.createTextNode("Character data contents for a new Element.");
getElementById: elementID2
This method returns the Element node with the given value for its ID attribute.
NOTE: It is important not to confuse attributes that have the name ID with ID attributes. ID attributes are attributes that were declared with the ID attribute type within the document type definition. See the Attribute List Declaration section in Chapter 20 for more information about ID attributes.Argument
- elementID: DOMString
- The unique ID value for the desired element.
Return value
A single Element object that has the requested ID attribute or null, if no match is found.
Java binding
public Element getElementById(String elementId);
getElementsByTagName: tagName
This function returns a list of Element nodes from the current document whose tagName attribute matches the given tagName parameter. The nodes are returned in the same order in which they appear in the source document.
Argument
- tagName: DOMString
- The name of the tag to use as a filter. The special name * matches any tag.
Java binding
public NodeList getElementsByTagName(String tagName);Java example
// Get a list of all phone numbers in the document NodeList nl = doc.getElementsByTagName("phone_number");
getElementsByTagNameNS: namespaceURI, localName2
Like the getElementsByTagName( ) method, this method returns a list of Element nodes (a NodeList object) that match the criteria given in the namespaceURI and localName parameters. The resulting list contains all elements matching the namespace URI and local name restrictions, as they would be encountered in the original order of the document on which the tree was constructed.
Arguments
- namespaceURI: DOMString
- The namespace URI of the elements to be matched. The special * value matches any namespace.
- localName: DOMString
- The local name part of the elements to be matched. The special value * matches any local name.
Java binding
public NodeList getElementsByTagNameNS(String namespaceURI, String localName);
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.
The new (copied) node object is returned based on the arguments.
Node type
Result
Effect of deep flag
ATTRIBUTE_NODECopies 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_NODECreates an empty DocumentFragment node.
Fully copies the children of the source DocumentFragment node.
DOCUMENT_NODECannot be imported.
N/A.
DOCUMENT_TYPE_NODECannot be imported.
N/A.
ELEMENT_NODECopies the attribute nodes with the specified flag set to the new element.
Recursively copies all the source element's children.
ENTITY_NODECopies the publicId, systemId, and notationName attributes.
Recursively copies all of the Entity node's children.
ENTITY_REFERENCE_NODECopies only the EntityReference node. Its value, if any, is taken from the DTD of the document doing the import.
None.
NOTATION_NODEImports 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_ NODECopies the target and data values.
None.
TEXT_NODE, CDATA_SECTION_NODE, COMMENT_NODECopies the data and length attributes.
None.
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;
| DocumentFragment |
The DocumentFragment is a lightweight container used to store XML document fragments temporarily. Since it has no properties or methods of its own, it can only provide the same functionality exposed by the Node object. It is intended to serve as a container for at least one well-formed XML subtree.
This object's most obvious application is in the case of clipboard or drag-and-drop operations in a visual editor. The user may elect to select several sub-trees that appear at the same level of the tree to be copied:
<xml_example>
<caption><filename>sample.xml</filename> before DocumentFragment
copy operation</caption>
<document>
<parent>
<child_1></child_1>
<child_2></child_2>
</parent>
<parent>
</parent>
</document>
</xml_example>If the user decides to copy the two child nodes to the clipboard, the DOM application would:
Create a DocumentFragment object.
Attach copies of the child nodes to the new object using the cloneNode( ) and appendChild( ) methods.
<xml_example>
<caption>DocumentFragment object on clipboard.</caption>
<DocumentFragment frame="dashed">
<child_1></child_1>
<child_2></child_2>
</DocumentFragment>
</xml_example>
Then, when the user decides to paste the copied nodes to a new location, the new DocumentFragment node is passed to this target node's appendChild( ) method. During the copy operation, the DocumentFragment node itself is ignored, and only the children are attached to the target node.
<xml_example>
<caption><filename>sample.xml</filename> after DocumentFragment copy
operation</caption>
<document>
<parent>
<child_1></child_1>
<child_2></child_2>
</parent>
<parent>
<child_1></child_1>
<child_2></child_2>
</parent>
</document>
</xml_example>
// Create a Document Fragment object DocumentFragment dfNorm = doc.createDocumentFragment( );
| DocumentType |
The Document interface includes a single attribute, docType, that points either to a description of the DTD for the current document or to null if none exists.
// get document type information
DocumentType dtDoc = doc.getDoctype( );
The DocumentType object contains the following attributes:
entities: NamedNodeMap
This attribute provides a list of all general entities declared in the document's DTD. If the same entity is declared more than once within a single document, only the first occurrence is preserved in this NamedNodeMap. Note that parameter entity declarations are not available through the DocumentType interface. Each member of this list implements the Entity interface. Read-only.
Java binding
public NamedNodeMap getEntities( );Java example
// Dump the document entities NamedNodeMap nnm = doc.getDoctype().getEntities( ); Entity ndEnt; for (int i = 0; i < nnm.getLength( ); i++) { ndEnt = (Entity)nnm.item(i); System.out.println(ndEnt.getNodeName( )); if (ndEnt.getPublicId( ) != null) { System.out.println("\tPublic Identifier: " + ndEnt.getPublicId( )); } if (ndEnt.getSystemId( ) != null) { System.out.println("\tSystem Identifier: " + ndEnt.getSystemId( )); } if (ndEnt.getNotationName( ) != null) { System.out.println("\tNotation Name: " + ndEnt.getNotationName( )); } }
name: DOMString
This is the name of the DTD, which is the XML name following the XML DOCTYPE keyword in the source document. Read-only.
Java binding
public String getName( );Java example
// Display document type information DocumentType dtDoc = doc.getDoctype( ); System.out.println("This is a " + dtDoc.getName( ) + " document.");
notations: NamedNodeMap
A NamedNodeMap contains a list of XML notation declarations for the current document. Each member of this list implements the Notation interface, and the list itself is read-only.
Java binding
public NamedNodeMap getNotations( );Java example
// Dump the document notations NamedNodeMap nnm = doc.getDoctype().getNotations( ); Notation ndNotation; for (int i = 0; i < nnm.getLength( ); i++) { ndNotation = (Notation)nnm.item(i); System.out.println(ndNotation.getNodeName( )); if (ndNotation.getPublicId( ) != null) { System.out.println("\tPublic Identifier: " + ndNotation.getPublicId( )); } if (ndNotation.getSystemId( ) != null) { System.out.println("\tSystem Identifier: " + ndNotation.getSystemId( )); } }
| DOMException |
For languages and runtime platforms that support them, structured exceptions provide a way to separate the code that deals with abnormal or unexpected problems from the normal flow of execution. For languages that don't support exceptions, such as ECMAScript or Perl, these conditions are reported to your program as error codes from the method that recognized the condition.
The ExceptionCode is an integer value that indicates what type of exception was detected. The following ExceptionCodes are defined, with unused numeric codes reserved for future use by the W3C:
INUSE_ATTRIBUTE_ERR [unsigned short, value: 10 ]
An attempt was made to add an attribute that was already in use elsewhere. This error could occur if you acquired an attribute via the getAttributeNode( ) method and tried to add the same object instance to another element using the setAttributeNode( ) method. You would first need to create a new Attr object, probably using the cloneNode( ) method.
Java binding
public static final short INUSE_ATTRIBUTE_ERR = 10;
NAMESPACE_ERR [unsigned short, value: 14]2
An attempt was made to use a method that supports XML namespaces in a way that would violate namespace rules. This error could occur if a qualified name were given to a method without a corresponding namespace URI.
Java binding
public static final short NAMESPACE_ERR = 14;
| DOMImplementation |
The DOMImplementation interface provides global information about the DOM implementation you currently use. The only way to obtain a reference to the DOMImplementation interface is through the getImplementation( ) method of the Document object.
// Check for DOM Level 1 support
DOMImplementation di = doc.getImplementation( );
// make sure that DOM Level 1 XML is supported
if (!di.hasFeature("XML", "1.0")) {
return null;
}
The DOMImplementation object defines the following methods:
createDocument: namespaceURI, qualifiedName, doctype2
Creates a new, empty Document object with the given document type. It also creates the single, top-level document element using the given qualified name and namespace URI.
Arguments
- namespaceURI: DOMString
- The namespace URI used to create the top-level document element. Can be null if no namespace is used.
- qualifiedName: DOMString
- The namespace-aware qualified name of the top-level document element to be created. The prefix given in this parameter is associated with the namespace URI given in the namespaceURI parameter.
- doctype: DOMString
- The document type definition object to be associated with the new document. If this parameter is not null, the DocumentType node's ownerDocument attribute is set to point to the new document object.
Exceptions
- INVALID_CHARACTER_ERR
- Indicates that the qualifiedName parameter has a malformed XML identifier.
- NAMESPACE_ERR
- Raised if an inconsistency exists between the values given for the namespaceURI and the qualifiedName parameters. Passing in a qualified name with a namespace prefix and not passing in a namespace URI is illegal. This can also be generated if a reserved namespace prefix, such as "xml", is given with an incorrect namespace URI.
- WRONG_DOCUMENT_ERR
- Raised if the DocumentType node passed in the doctype parameter is already associated with another document object. New DocumentType objects must be created using the new createDocumentType method of the DOMImplementation interface.
Java binding
public Document createDocument(String namespaceURI, String qualifiedName, DocumentType doctype) throws DOMException;
createDocumentType: qualifiedName, publicId, systemId2
Creates an empty DocumentType node that is not associated with any document. No entity declarations or notations are available in this new, empty DocumentType object. No support currently exists in the DOM to populate this object.
Arguments
- qualifiedName: DOMString
- The qualified name of the document type to be created.
- publicId: DOMString
- The external subset's public identifier.
- systemId: DOMString
- The system identifier (URI) of the external subset to be created.
Return value
A new DocumentType object with the ownerDocument attribute set to null.
Exceptions
- INVALID_CHARACTER_ERR
- Indicates that the qualifiedName parameter has a malformed XML identifier.
- NAMESPACE_ERR
- Raised if the qualified name is malformed.
Java binding
public DocumentType createDocumentType(String qualifiedName, String publicId, String systemId) throws DOMException;
hasFeature: feature, version
Tests to see if the DOM implementation supports a given named feature package. It returns true if the particular version of the specified feature is available; otherwise, returns false.
Arguments
- feature: DOMString
- The package name of the feature to test. The following feature names (and others listed at http://www.w3.org/TR/DOM-Level-2-Core/introduction.html-ID-Conformance) are valid:
- XML
- Supports DOM Level 1.0 or 2.0 Core objects.
- HTML
- Supports DOM Level 1.0 or 2.0 HTML objects.
- version: DOMString
- Represents the DOM version level of the specified feature to test. If no versionnull number is specified, the function returns true if any version is supported.
Java binding
public boolean hasFeature(String feature, String version);Java example
// Make sure that DOM Level 1 XML is supported if (!di.hasFeature("XML", "1.0")) { return null; }NOTE: The HTML-specific DOM objects are beyond the scope of this book, but they are extremely useful tools for building applications that perform transformations on HTML documents. An excellent reference to the HTML DOM objects can be found in the book Dynamic HTML: The Definitive Reference, by Danny Goodman (O'Reilly & Associates).
| Element |
The Element object type provides access to the XML document's structure and data. Every XML element is translated into a single Element node. The document's root element is accessible through the documentElement property of the Document object. From this node, it is possible to re-create the full structure of the original XML document by traversing the element tree.
// Get the XML document's root element Element elem = doc.getDocumentElement( );
This interface extends the basic Node interface to allow access to the XML attributes of the document element. Two sets of methods allow access to attribute values, either as Attr object trees or as simple DOMStrings.
The Element object defines one attribute that contains the XML tag name:
| Element (continued) |
The following methods are defined for this object:
getAttribute: name
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"); }
getAttributeNS: namespaceURI, localName2
Returns an attribute as a DOMString, based on the namespace and local part of the qualified name.
Arguments
- namespaceURI: DOMString
- The namespace URI of the attribute to return.
- localName: DOMString
- The local name portion of the qualified attribute name to return.
Return value
Returns an empty string if no attribute is set and if no default attribute value was specified in the DTD.
Java binding
public String getAttributeNS(String namespaceURI, String localName);
getAttributeNode: name
Retrieves the Attr for the name attribute. Returns a reference to the attribute object if it is found; otherwise, null.
Arguments
- name: DOMString
- Name of the attribute to retrieve.
Java binding
public Attr getAttributeNode(String name);Java example
// Use the id attribute Attr attr; if ((attr = elem.getAttributeNode("id")) == null) { System.out.println("warning: element " + elem.getTagName( ) + ": no id attribute provided."); }
getAttributeNodeNS: namespaceURI, localName2
Retrieves the Attr object for the attribute specified by the given namespace URI and local name. Returns a reference to the attribute object if it is found; otherwise returns null.
Arguments
- namespaceURI: DOMString
- Namespace URI of the target attribute.
- localName: DOMString
- Local name of the target attribute. The local name is the part of the name to the right of the : in a qualified name.
Java binding
public Attr getAttributeNodeNS(String namespaceURI, String localName);
getElementsByTagName: name
Returns a NodeList of all descendant Element nodes whose tagName attribute matches the given name parameter. The nodes are returned in the same order in which they would be encountered in a preorder traversal of the document tree. A preorder traversal conforms to the order in which the XML elements appear in the source document.
Argument
- name: DOMString
- The name of the tag to use as a filter. The special name * matches any tag.
Java binding
public NodeList getElementsByTagName(String name);Java example
// Find every address element in the document Element elem = doc.getDocumentElement( ); NodeList nlAddrs = elem.getElementsByTagName("address");
getElementsByTagNameNS: namespaceURI, localName2
Like the getElementsByTagName method, returns a list of Element nodes, descendants of the Element node on which the method is called, that match the criteria given in the namespaceURI and localName parameters. The resulting list contains all elements matching the namespace URI and local name restrictions, as they would be encountered in a preorder traversal of the document tree.
Arguments
- namespaceURI: DOMString
- The namespace URI of elements to be matched. The special * value matches any namespace.
- localName: DOMString
- The local name part of elements to be matched. The special value * matches any local name.
Java binding
public NodeList getElementsByTagNameNS(String namespaceURI, String localName);
hasAttributeNS: namespaceURI, localName2
Returns true if an attribute with the given namespaceURI and localName has been set or has a default value. Returns false if the attribute isn't defined.
Arguments
- namespaceURI: DOMString
- The namespace URI of the attribute to be identified.
- localName: DOMString
- The local name of the attribute to be identified.
Java binding
public boolean hasAttribute(String namespaceURI, String localName);
normalize
Traverses the subtree of the current Element, combining adjacent Text nodes into a single node.
NOTE: This method was moved to the Node interface as part of the DOM Level 2 specification. It is still accessible from the Element interface, as it inherits from the Node interface.Java binding
public void normalize( );Java example
// Merge all adjacent text nodes below this element elem.normalize( );
removeAttribute: name
Removes the named element attribute from this element's attributes collection. If the attribute to be removed has a default value declared in the DTD, subsequent attempts to retrieve the attribute value return the default value.
Argument
- name: DOMString
- Name of the attribute to remove.
Exception
- NO_MODIFICATION_ALLOWED_ERR
- Raised if the element is read-only.
Java binding
public void removeAttribute(String name) throws DOMException;Java example
// Remove the unique ID ... elem.removeAttribute("id"); ...
removeAttributeNS: namespaceURI, localName2
Uses the given namespace URI and local name parameters to remove the desired attribute from the element's attributes collection.
Arguments
- namespaceURI: DOMString
- Namespace URI of the target attribute.
- localName: DOMString
- Local name part of the target attribute. The local name is the part to the right of the final : in a qualified name.
Exception
- NO_MODIFICATION_ALLOWED_ERR
- Raised if the element is read-only.
Java binding
public void removeAttributeNS(String namespaceURI, String localName) throws DOMException;
removeAttributeNode: oldAttr
Removes the referenced attribute node from this element's attributes collection. If the attribute to be removed has a default value declared in the DTD, subsequent attempts to retrieve the attribute value return the default value.
Argument
- oldAttr: Attr
- The attribute node to remove.
Exceptions
- NO_MODIFICATION_ALLOWED_ERR
- Raised if the node is read-only.
- NOT_FOUND_ERR
- Raised if no attribute name matching the oldAttr parameter is found in the map.
Java binding
public Attr removeAttributeNode(Attr oldAttr) throws DOMException;Java example
// Find and remove temporary attributes Attr attr; if ((attr = elem.getAttributeNode("temp")) != null) { // remove it elem.removeAttributeNode(attr); }
setAttribute: name, value
Sets the attribute specified by the name parameter to the DOMString passed in the value argument. The string is not parsed for entity references and is set as a Text node child of the corresponding member of the attributes collection. If an attribute with the given name already exists, the value is set to the value argument.
Arguments
- name: DOMString
- The attribute name to set or modify.
- value: DOMString
- The new attribute value.
Exceptions
- INVALID_CHARACTER_ERR
- Indicates that the attribute name you passed in doesn't represent a valid XML attribute name.
- NO_MODIFICATION_ALLOWED_ERR
- Raised if the element is read-only.
Java binding
public void setAttribute(String name, String value) throws DOMException;Java example
// Check for the name attribute if (elem.getAttribute("name") == "") { // oh well, set a reasonable default elem.setAttribute("name", elem.getTagName( )); }
setAttributeNS: namespaceURI, qualifiedName, value2
This method is the namespace-enabled version of the basic setAttribute method. The namespace URI and the qualified name update the attributes collection of the element in question.
Arguments
- namespaceURI: DOMString
- The namespace URI of the attribute value to set.
- qualifiedName: DOMString
- The qualified name (including namespace prefix) of the new value to set.
- value: DOMString
- The new attribute value.
Exceptions
- INVALID_CHARACTER_ERR
- Indicates that the attribute name you passed in doesn't represent a valid XML attribute name.
- NO_MODIFICATION_ALLOWED_ERR
- Raised if the element is read-only.
- NAMESPACE_ERR
- Raised if the namespaceURI and qualifiedName parameters would violate rules concerning namespaces. If the qualified name includes a prefix, the namespace URI cannot be null or an empty string. If the reserved xml or xmlns prefixes are used, the namespace URI must match the corresponding specified system URI. See Chapter 4 for more information about namespaces and prefixes.
Java binding
public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException;
setAttributeNode: newAttr
Sets or replaces the attribute in the Node interface's attributes collection with the given Attr object. The attribute name is retrieved from the name attribute of the new attribute object. If an Attr object with the given name already exists in the attributes collection, this method returns a reference to the old Attr object. Otherwise, it returns null.
Argument
- newAttr: Attr
- The new Attr object to set.
Exceptions
- WRONG_DOCUMENT_ERR
- Raised if the newAttr node was created in a document different than the parent node.
- NO_MODIFICATION_ALLOWED_ERR
- Raised if the new parent node is read-only.
- INUSE_ATTRIBUTE_ERR
- Raised if another Element already uses the new Attr node. Each element must have a distinct Attr object.
Java binding
public Attr setAttributeNode(Attr newAttr) throws DOMException;Java example
// Make sure you have an id attribute to work with Attr attr; if ((attr = elem.getAttributeNode("id")) == null) { // add a default, unique id attr = doc.createAttribute("id"); elem.setAttributeNode(attr); // continue processing }
setAttributeNodeNS: newAttr2
Sets or replaces the attribute in the element's attributes collection that matches the namespace URI and the given Attr object's local name. This operation is identical to the setAttributeNode method, except that it considers namespace differences between attributes. If an Attr object with the given name in the attributes collection already exists, this method returns a reference to the old Attr object; otherwise, it returns null.
Argument
- newAttr: Attr
- The new Attr object to set.
Exceptions
- WRONG_DOCUMENT_ERR
- Raised if the newAttr node was created in a different document than the parent node.
- NO_MODIFICATION_ALLOWED_ERR
- Raised if the new parent node is read-only.
- INUSE_ATTRIBUTE_ERR
- Raised if another Element already uses the newAttr node. Each element must have a unique Attr object.
Java binding
public Attr setAttributeNodeNS(Attr newAttr) throws DOMException;
| Entity |
The Entity object represents a given general XML entity's replacement value. Depending on whether a given DOM implementation is validating or nonvalidating and whether it chooses to expand entity references inline during parsing, Entity objects may not be available to the DOM user.
// Locate the my_entity entity declaration
Entity ndEnt = (Entity)doc.getDoctype().getEntities( ).
getNamedItem("my_entity");
The following read-only attributes are defined for the Entity object:
publicId: DOMString
The public identifier URL (URI) given for this entity, or null if none was specified.
Java binding
public String getPublicId( );Java example
// Locate the my_entity entity declaration Entity ndEnt = (Entity)doc.getDoctype().getEntities( ).getNamedItem("my_ entity"); // if my_entity type was found and there is a public-ID (URL)... if (ndEnt != null && ndEnt.getPublicId( ) != null) { try { // ...get the URL protocol URL urlSys = new URL(ndEnt.getPublicId( )); System.out.println("Entity " + ndEnt.getNodeName( ) + ": protocol " + urlSys.getProtocol( )); } catch (MalformedURLException e) { } }
systemId: DOMString
The system identifier URL (URI) given for this entity, or null if none was specified.
Java binding
public String getSystemId( );Java example
// Get the Public ID or System ID for this entity Entity ndEnt = (Entity)doc.getDoctype().getEntities( ).getNamedItem("my_ entity"); String strURL = ndEnt.getPublicId( ); // if can't find the public URL if (strURL == null) { // find the system URL strURL = ndEnt.getSystemId( ); }
| EntityReference |
EntityReference nodes appear within the document hierarchy wherever an XML general entity reference is embedded within the source document. Depending on the DOM implementation, a corresponding Entity object may exist in the entities collection of the docType attribute of the Document object. If such an entity exists, then the child nodes of both the Entity and EntityReference represent the replacement text associated with the given entity.
// Create a new entity reference
EntityReference ndER = doc.createEntityReference("my_entity");
| NamedNodeMap |
The NamedNodeMap interface provides a mechanism used to retrieve Node objects from a collection by name. Though this interface exposes the same methods and attributes as the NodeList class, they are not related. While it is possible to enumerate the nodes in a NamedNodeMap using the item( ) method and length attribute, the nodes are not guaranteed to be in any particular order.
// Get an element's attributes NamedNodeMap nnm = elem.getAttributes( );
The NamedNodeMap defines one attribute:
| NamedNodeMap (continued) |
The following methods are defined for the NamedNodeMap object:
getNamedItem: name
Returns a reference to the node with the given nodeName property specified by name.
Argument
- name: DOMString
- Name of the node to retrieve.
Java binding
public Node getNamedItem(String name);Java example
// Check to see if an ID attribute exists // in this map, and add it if necessary // nnm was created by getting the attributes // from an element if (nnm.getNamedItem("id") == null) { // get the document Document doc = elem.getOwnerDocument( ); // crea