Chapter 24. DOM Reference

CONTENTS

  •  24.1 Object Hierarchy
  •  24.2 Object 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.

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.

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.

24.1 Object Hierarchy

The following table shows the DOM object hierarchy:

Object

Permitted child objects

Document

Element (one is the maximum)

ProcessingInstruction

Comment

DocumentType (one is the maximum)

DocumentFragment
Element ProcessingInstruction Comment Text CDATASection EntityReference
DocumentType

None (leaf node)

EntityReference
Element ProcessingInstruction Comment Text CDATASection EntityReference
Element
Element Text Comment ProcessingInstruction CDATASection EntityReference
Attr
Text EntityReference
ProcessingInstruction 

None (leaf node)

Comment

None (leaf node)

Text

None (leaf node)

CDATASection

None (leaf node)

Entity
Element ProcessingInstruction Comment Text CDATASection EntityReference
Notation

None (leaf node)

24.2 Object Reference

This section details the XML DOM Level 2 Core objects. The reference sections detail the descriptions, attributes, and methods of each object in the language- independent IDL specification. Java examples and bindings are presented to illustrate usage.

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");

Attributes

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( ));     }
ownerElement: Element2  

   

This property provides a link to the Element object that owns this attribute. If the attribute is currently unowned, it equals null. Read-only.

Java binding

public Element getOwnerElement( );
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.

Java example

// 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.

Java example

// 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;

Attributes

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)  


   

Methods

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.

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.

Java example

// 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.

Attributes

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)  


   

Methods

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.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;
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 &amp;, &lt;, or &gt;.

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.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");
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.

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.

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;
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>

Java 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.

Java example

// get document type information     DocumentType dtDoc = doc.getDoctype( );

Attributes

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( ));     } }
internalSubset: DOMString  

   

This attribute contains the document's internal subset as a string value. The content's actual format depends on the level of support provided by a particular XML parser. Read-only.

Java binding

public String getInternalSubset( );
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( ));     } }
publicId: DOMString  

   

This is the public identifier of the external subset. Read-only.

Java binding

public String getPublicId( );
systemId: DOMString  

   

The system identifier (URI) of this document's external subset. Read-only.

Java binding

public String 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:

INDEX_SIZE_ERR [unsigned short, value: 1]  

   

An index outside the expected range was passed to a method that accepts an index. The expected range for most collections is 0 <= index < collection. length.

Java binding

public static final short INDEX_SIZE_ERR = 1;
DOMSTRING_SIZE_ERR [unsigned short, value: 2]  

   

The DOMString that would be returned from a method is too large.

Java binding

public static final short DOMSTRING_SIZE_ERR = 2;
HIERARCHY_REQUEST_ERR [unsigned short, value: 3 ]  

   

The node insertion you requested violates the document structure's integrity. For example, the insertion would cause a node to become one of its own children.

Java binding

public static final short HIERARCHY_REQUEST_ERR = 3;
WRONG_DOCUMENT_ERR [unsigned short, value: 4 ]  

   

An attempt to insert a node from one document directly into another. A given implementer of the DOM framework determines whether this insertion generates an error.

Java binding

public static final short WRONG_DOCUMENT_ERR = 4;
INVALID_CHARACTER_ERR [unsigned short, value: 5 ]  

   

An invalid character was used in a name, e.g., trying to create an Element object with the name "my element", as spaces are not allowed.

Java binding

public static final short INVALID_CHARACTER_ERR = 5;
NO_DATA_ALLOWED_ERR [unsigned short, value: 6 ]  

   

Data was assigned to a node that doesn't support data, like an Element node.

Java binding

public static final short NO_DATA_ALLOWED_ERR = 6;
NO_MODIFICATION_ALLOWED_ERR [unsigned short, value: 7 ]  

   

An attempt was made to modify a node that cannot be modified.

Java binding

public static final short NO_MODIFICATION_ALLOWED_ERR = 7;
NOT_FOUND_ERR [unsigned short, value: 8 ]  

   

A node was modified in a context in which it could not be found.

Java binding

public static final short NOT_FOUND_ERR = 8;
NOT_SUPPORTED_ERR [unsigned short, value: 9 ]  

   

If in the specific implementation of the DOM you chose not to implement an optional feature, this exception would be thrown.

Java binding

public static final short NOT_SUPPORTED_ERR = 9;
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;
INVALID_STATE_ERR [unsigned short, value: 11]2  

   

An attempt was made to use an object that is no longer usable.

Java binding

public static final short INVALID_STATE_ERR = 11;
SYNTAX_ERR [unsigned short, value: 12]2  

   

An invalid or illegal string was specified.

Java binding

public static final short SYNTAX_ERR = 12;
INVALID_MODIFICATION_ERR [unsigned short, value: 13]2  

   

An attempt was made to change the type's underlying object.

Java binding

public static final short INVALID_MODIFICATION_ERR = 13;
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;
INVALID_ACCESS_ERR [unsigned short, value: 15]2  

   

The underlying object does not support a parameter or operation.

Java binding

public static final short INVALID_ACCESS_ERR = 15;
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.

Java example

// 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; }

Methods

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; }

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.

Java example

// 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.

Attribute

The Element object defines one attribute that contains the XML tag name:

tagName: DOMString  

   

The XML tag name from the original document.

Java binding

public String getTagName( ); // Show the name of the root element tag Element elem = doc.getDocumentElement( ); System.out.println("This is a " + elem.getTagName( ) + " document.");
Element (continued)  


   

Methods

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);
hasAttribute: name2  

   

Returns true if an attribute with the given name has been set or has a default value. Returns false if the attribute isn't defined.

Argument

name: DOMString

The name of the attribute to be identified.

Java binding

public boolean hasAttribute(String name);
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.

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.

Java example

// Locate the my_entity entity declaration Entity ndEnt = (Entity)doc.getDoctype().getEntities( ).     getNamedItem("my_entity");

Attributes

The following read-only attributes are defined for the Entity object:

notationName:  

   

If this entity is unparsed, the entity's notation name. For parsed entities, this attribute is null.

Java binding

public String getNotationName( );

Java example

// Find out if it's a parsed entity boolean fParsedEnt = ndEnt.getNotationName( ) == null;
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.

Java example

// 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.

Java example

// Get an element's attributes NamedNodeMap nnm = elem.getAttributes( );

Attribute

The NamedNodeMap defines one attribute:

length: unsigned long  

   

The total number of Node objects in the list.

Java binding

public long getLength( );

Java example

// Iterate over the attribute list for (int i = 0; i < nnm.getLength( ); i++) {     ... }
NamedNodeMap (continued)  


   

Methods

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( );     // 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); }
getNamedItemNS: namespaceURI, localName2  

   

Extends the basic getNamedItem method to include support for namespaces. Instead of finding an item in the list based only on the local part of the node name, it is possible to incorporate the namespace URI into the search.

Arguments

namespaceURI: DOMString

Namespace URI of the node to retrieve.

localName: DOMString

Local name of the node to retrieve.

Java binding

public Node getNamedItemNS(String namespaceURI, String localName);
item: index  

   

Returns a reference to the Node object at position index. If the given index is < 0 or >= the length attribute of the NodeList, this function returns null.

Argument

index: unsigned long

Zero-based index of the list of the node to return.

Java binding

public Node item(long index);

Java example

// Remove the last attribute from the list if (nnm.getLength( ) > 0) {     nnm.removeNamedItem(nnm.item(nnm.getLength()-1).getNodeName( )); }
removeNamedItem: name  

   

Removes the Node object with the nodeName property that matches the name parameter and returns a reference to the removed object. If the node you plan to remove is an Attr node and if it has a defined default value, the node will be replaced immediately with a new Node object set to the default value.

Argument

name: DOMString

The nodeName value of the node to be removed.

Exception

NOT_FOUND_ERR

Raised if no node matching the name parameter is found in the map.

Java binding

public Node removeNamedItem(String name) throws DOMException;

Java example

// Remove the ID node attribute NamedNodeMap nnm = elem.getAttributes( ); if (nnm.removeNamedItem("id") == null) {     System.err.println("no ID attribute found"); }
removeNamedItemNS: namespaceURI, localName2  

   

Removes the Node object with the matching namespaceURI and localName properties and returns a reference to the removed object. If the node you plan to remove is an Attr node and if it has a defined default value, a new Node object set to the default value will replace the node immediately.

Arguments

namespaceURI: DOMString

Namespace URI of the node to retrieve.

localName: DOMString

Local name of the node to retrieve.

Exception

NOT_FOUND_ERR

Raised if no node matching the namespaceURI and localName parameter is found in the map.

Java binding

public Node removeNamedItemNS(String namespaceURI, String localName);
setNamedItem: arg  

   

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); }
setNamedItemNS: arg2  

   

Identical in function to the basic setNamedItem method, except that it considers namespace properties in the Node object. A reference to the replaced Node object is returned.

Argument

arg: Node

The Node object to be stored in the map. The values of the namespaceURI and localName properties are used as the lookup key. If another node with identical values for these two properties exists, the new node replaces it.

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 already in use by another element's attributes map.

Java binding

public Node setNamedItemNS(Node arg) throws DOMException;
Node  


   

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.

attributes: NamedNodeMap  

   

Has meaning only for Element objects. It provides access to a list of Attr objects in a NamedNodeMap. For all other object types, it returns null.

Java binding

public NamedNodeMap getAttributes( ); // List the attributes of an Element node NamedNodeMap nnm = doc.getDocumentElement().getAttributes( ); if (nnm != null) {     for (int i = 0; i < nnm.getLength( ); i++) {         // print the attribute and value         System.out.println(nnm.item(i).getNodeName( ) + " = \"" +                            nnm.item(i).getNodeValue( ) + "\"");     } }
childNodes: NodeList  

   

Returns a NodeList containing a reference to every child of this Node.

Java binding

public NodeList getChildNodes( );

Java example

// List the text contents of an element NodeList nlChildren = elem.getChildNodes( ); Node ndChild; for (int iNode = 0; iNode < nlChildren.getLength( ); iNode++) {     ndChild = nlChildren.item(iNode);     if (ndChild.getNodeType( ) == Node.TEXT_NODE) {         System.out.println(ndChild.getNodeValue( ));     } }   

Dynamic Tree References

Throughout the DOM, several places return lists or collections of nodes that represent the current state of the document tree. These references are all live; any modifications to the document hierarchy, made by inserting or removing nodes, are reflected in the list immediately.

Whether due to multithreading or unforeseen side effects of procedure calls, the contents of the list being used could change. To reduce the likelihood of difficult-to-find bugs resulting from stale values, request values (such as the length of a list) directly from the NodeList or NamedNodeMap objects. This option is safer than storing values in intermediate variables.

firstChild: Node  

   

Points to the head of the linked list of children of this node. If no child nodes exist, it returns null.

Java binding

public Node getFirstChild( );

Java example

// List the contents of a node for (Node nd = ndDump.getFirstChild( ); nd != null;      nd = nd.getNextSibling( )) {     if (nd.getNodeValue( ) != null) {         System.out.println(nd.getNodeValue( ));     } }
lastChild: Node  

   

Returns a pointer to the end of a given Node object's linked list of child nodes. If no children exist, it returns null.

Java binding

public Node getLastChild( );

Java example

// List the value of a node in reverse order for (Node nd = ndDump.getLastChild( ); nd != null;      nd = nd.getPreviousSibling( )) {     if (nd.getNodeValue( ) != null) {         System.out.println(nd.getNodeValue( ));     } }
localName: DOMString2  

   

Returns the local part of the fully qualified node name. This part of the name is to the right of the final : in a namespace-qualified name.

Java binding

public String getLocalName( );
namespaceURI: DOMString2  

   

Represents the namespace URI given to this Node object at creation time; returns null if no namespace was given. The value is null if the node's been created by a createNodeType( ) method rather than a createNodeTypeNS( ) method.

Java binding

public String getNamespaceURI( );
nextSibling: Node  

   

Returns the next node in the sibling list. If this node is the end of the list, nextSibling returns null.

Java binding

public Node getNextSibling( );

Java example

// List the contents of a node for (Node nd = ndDump.getFirstChild( ); nd != null;      nd = nd.getNextSibling( )) {     if (nd.getNodeValue( ) != null) {         System.out.println(nd.getNodeValue( ));     } }
nodeName: DOMString  

   

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:

Object type

nodeName

Element

Tag name

Attr

Attribute name

Text

"#text"

CDATASection

"#cdata-section"

EntityReference

Name of entity referenced

Entity

Entity name

ProcessingInstruction

Target

Comment

"#comment"

Document

"#document"

DocumentType

Document type name

DocumentFragment

"#document-fragment"

Notation

Notation name

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( ));
nodeType: unsigned short  

   

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:

Constant name

Object type

Constant value

ELEMENT_NODE

Element

1

ATTRIBUTE_NODE

Attr

2

TEXT_NODE

Text

3

CDATA_SECTION_NODE

CDATASection

4

ENTITY_REFERENCE_NODE

EntityReference

5

ENTITY_NODE

Entity

6

PROCESSING_INSTRUCTION_NODE

ProcessingInstruction

7

COMMENT_NODE

Comment

8

DOCUMENT_NODE

Document

9

DOCUMENT_TYPE_NODE

DocumentType

10

DOCUMENT_FRAGMENT_NODE

DocumentFragment

11

NOTATION_NODE

Notation

12

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; }
nodeValue: DOMString  

   

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.

Object type

nodeValue

Element

null

Attr

Attribute value

Text

Text node content

CDATASection

CDATA section content

EntityReference

null

Entity

null

ProcessingInstruction

Entire content, excluding the target

Comment

Comment content

Document

null

DocumentType

null

DocumentFragment

null

Notation

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( )); }
ownerDocument: Document  

   

Returns a reference to the Document used to create this Node object. Since the Document object is the only mechanism exposed for creating new nodes, even these newly created, empty nodes have the ownerDocument property set. This attribute can be null only for Document nodes and DocumentType nodes that are not yet part of a document. You can't move a node directly to another document; instead you must import it. This property can be useful for checking where a node came from.

Java binding

public Document getOwnerDocument( );

Java example

// Add my two cents Document doc = elem.getOwnerDocument( ); Text txtAdd = doc.createTextNode("My $.02"); elem.appendChild(txtAdd);
parentNode: Node  

   

Provides a reference to the parent of this node. All node types, except Document, DocumentFragment, and Attr, may have a parent node. Every node within a Document hierarchy has a parent. Nodes that are not part of the document tree, such as new nodes and nodes removed from the document using the replaceChild( ) or removeChild( ) methods, have a parentNode attribute of null.

Java binding

Node getParentNode( );

Java example

// Unlink an element from the document tree elem.getParentNode( ).removeChild(elem);
prefix: DOMString2  

   

Represents the namespace prefix of this node, used for nodes that support namespace prefixes. For ELEMENT_NODE and ATTRIBUTE_NODE type nodes, changing the namespace prefix also affects the nodeName, tagName, and name attributes. Since these properties hold the qualified name of the node, changing the prefix also updates it.

Exceptions

INVALID_CHARACTER_ERR

Raised if the prefix includes an illegal character.

NO_MODIFICATION_ALLOWED_ERR

Indicates that the prefix attribute is read-only for this DOM object type.

NAMESPACE_ERR

Raised if the prefix is malformed, according to the rules of namespace identifier formation. This exception is also raised if the namespaceURI attribute is null, or if an attempt was made to violate the XML rules of identifier formation. Such an attempt includes invalid use of the xml or xmlns identifier. For more information about namespaces, see Chapter 4.

Java bindings

public String getPrefix( ); public void setPrefix(String prefix) throws DOMException;
previousSibling: Node  

   

Returns the preceding node in the sibling list. If this node is the head of the sibling list, it returns null.

Java binding

public Node getPreviousSibling( );

Java example

// List the value of a node in reverse order for (Node nd = ndDump.getLastChild( ); nd != null;      nd = nd.getPreviousSibling( )) {     if (nd.getNodeValue( ) != null) {         System.out.println(nd.getNodeValue( ));     } }
Node (continued)  


   

Methods

The following methods are defined for Node interface objects:

appendChild: newchild  

   

Appends the newchild node to the end of the child list. If newchild is already linked into the document tree, it is unlinked before the append is performed. This method returns a reference to the newchild node.

Argument

newchild: Node

The node to append. If the node is a DocumentFragment node, the children of newchild are appended in sequence to the end of the node's child list.

Exceptions

HIERARCHY_REQUEST_ERR

Raised if the insert operation violates 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 is created in a different document than that of the new parent node.

NO_MODIFICATION_ALLOWED_ERR

Raised if the new parent node is read-only.

Java binding

public Node appendChild(Node newChild) throws DOMException;

Java example

// Move the first child to the end of the child node list if (elem.getFirstChild( ) != null) {     elem.appendChild( elem.getFirstChild( ) ); }
cloneNode: deep  

   

Returns a copy of the node without a parent node. If the cloned node is specified as deep (true), the subtree under the node is also copied. Otherwise, the cloned node does not contain child nodes.

Argument

deep: boolean

If true, child nodes are copied to the cloned node. If false, only the original node is copied.

Java binding

public Node cloneNode(boolean deep);

Java example

// Make a copy of this element and all children elem.cloneNode(true);
hasAttributes ( )  

   

Indicates whether an Element node has any attributes. Returns true if the node has attributes; otherwise, it returns false.

Java binding

public boolean hasAttributes( );
hasChildNodes ( )  

   

Provides a quick way to determine if a node has children. Returns true if the node has any children; otherwise, it returns false.

Java binding

public boolean hasChildNodes( );
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);
normalize ( ) 2  

   

Recursively combines all adjacent Text nodes into a single node. It also removes empty Text nodes from the document tree. This operation is useful for operations that require absolute references within a document or if two documents must be compared.

Java binding

public void normalize( );
removeChild: oldchild  

   

Unlinks the oldchild node from the child list of a given node and returns a reference to the now detached Node object.

Argument

oldchild: Node

The node to be removed.

Exceptions

NO_MODIFICATION_ALLOWED_ERR

Raised if the parent node is read-only.

NOT_FOUND_ERR

Raised if the oldchild node is not a child of this node.

Java binding

public Node removeChild(Node oldChild) throws DOMException;

Java example

// Unlink an element and all its children // from the document tree elem.getParentNode( ).removeChild(elem);
replaceChild: newchild, oldchild  

   

Replaces the child node oldchild with newchild. If newchild is currently linked into the document tree, it is removed before the replace is performed. The method returns a reference to the oldchild node.

Arguments

newchild: Node

The node to be inserted.

oldchild: Node

The node being replaced.

Exceptions

HIERARCHY_REQUEST_ERR

Raised if the insert operation violates 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 different document than 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 oldchild is not a child of the node performing the replacement.

Java binding

public Node replaceChild(Node newChild, Node oldChild)                throws DOMException;

Java example

// Replace an old node with a new one ndOld.getParentNode( ).replaceChild(ndNew, ndOld);
NodeList  


   

The NodeList interface allows DOM classes to expose an ordered collection of nodes. A NodeList represents a read-only, zero-based array of Node objects. Since no mechanism exists for creating, adding, or removing nodes from a NodeList, DOM users cannot use this class as a general-purpose utility class.

Java example

// List the text contents of an element NodeList nlChildren = elem.getChildNodes( ); Node ndChild; for (int iNode = 0; iNode < nlChildren.getLength( ); iNode++) {     ndChild = nlChildren.item(iNode);     if (ndChild.getNodeType( ) == Node.TEXT_NODE) {         System.out.println(ndChild.getNodeValue( ));     } }

Attributes

The NodeList interface defines one attribute:

length: unsigned long  

   

The total number of Node objects in the list.

Java binding

public long getLength( );
NodeList (continued)  


   

Methods

The NodeList interface defines one method:

item:  

   

Returns a reference to the Node object at position index or returns null if the index is invalid. If the index given is < 0 or >= the length attribute of the NodeList, this function returns null.

Argument

index: unsigned long

Zero-based index into the list of the Node to return.

Java binding

public Node item(long index);
ProcessingInstruction  


   

This interface provides access to the contents of an XML processing instruction. Processing instructions provide a mechanism for embedding commands to an XML processing application that is in line with the XML content.

Java example

// Add an application-specific processing instruction ProcessingInstruction pi = doc.createProcessingInstruction("my_app",         "action=\"save\"");

Attributes

The interface defines two attributes:

data: DOMString  

   

Returns the data portion of this processing instruction. The data portion is identified starting at the first nonwhitespace character after the target token and ending at the closing ?>.

Write exception

NO_MODIFICATION_ALLOWED_ERR

Raised if the node is read-only.

Java bindings

public String getData( ); public void setData(String data) throws DOMException;

Java example

// Check the application's data attribute if (pi.getTarget( ) == "MY_APPLICATION") {     // check the data attribute for my own application-specific info     if (pi.getData( ) == "CHECK_SIBLINGS") {         // check the siblings         ...     }     pi.setData("SIBLINGS_CHECKED"); }
target: DOMString  

   

Returns the target portion of this processing instruction. The target is the first whitespace-delimited token within the processing-instruction block.

Processing instructions are meant to embed application-specific instructions for automatic content generation, parsing, etc., within the XML stream. The instruction's target portion is the flag that allows different processing applications to coexist. Applications that use processing instructions for formatting should ignore processing instructions they do not recognize.

Java binding

public String getTarget( ); // Check to see if your application is targeted if (pi.getTarget( ) == "MY_APPLICATION") {     // do my application-specific processing here }
Text  


   

Text nodes contain the nonmarkup character data contained within the XML document. After the XML document is parsed, exactly one Text node exists for each uninterrupted block of nonmarkup text:

<text_node>This is text.</text_node>

Method

The following method is defined for the Text interface:

splitText: offset  

   

Splits a Text node into two adjacent Text nodes. The contents of the original node are divided at the given split offset, with the second substring used as the new node's value. The first substring remains in the original node. If the node is currently linked into the DOM tree, the new node with the split content becomes the next sibling of the original node. A new Text node containing the second part of the split data is returned.

Argument

offset (unsigned long)

Zero-based offset where the split occurs.

Exceptions

INDEX_SIZE_ERR

Raised if the offset given is < 0 and >= the length attribute.

NO_MODIFICATION_ALLOWED_ERR

Raised if the element is read-only.

Java binding

public Text splitText(long offset) throws DOMException;

Java example

// Make one Text node long = doc.createTextNode("This text is split."); // and split it Text ndSplit = ndText.splitText(9);

Text is a subclass of the CharacterData interface. See the CharacterData interface section in this chapter for a list of applicable methods for accessing character data in nodes of this type.

CONTENTS


XML in a Nutshell
XML in a Nutshell, 2nd Edition
ISBN: 0596002920
EAN: 2147483647
Year: 2001
Pages: 28

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net