![]() | CONTENTS | ![]() |
|
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.
|
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.
|
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.
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) |
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");
The following attributes are defined for the Attr object:
name: DOMString |
The name of the attribute. Read-only.
Public String getName( );
// 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.
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.
public boolean getSpecified( );
// 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.
public String getValue( ); public void setValue(String value);
// 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.
Raised on a write attempt when the data attribute is read-only for this DOM object type.
Raised if the read value that would be returned is too large to be contained by a DOMString type in the given implementation.
public String getData( ) throws DOMException; public void setData(String data) throws DOMException;
// 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.
public long getLength( );
// 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.
The string to append.
Raised if this node is read-only.
public void appendData(String arg) throws DOMException;
// 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.
The position in the data attribute to remove count characters.
The count of characters to remove. If the offset + count is >= the length attribute, the remainder, starting at position offset, is deleted.
Raised if the offset parameter is not a valid zero-based index into the data DOMString.
Raised if the node is read-only.
public void deleteData(long offset, long count) throws DOMException;
// 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.
The zero-based offset in the data attribute where the insertion is made.
The string to be inserted.
Raised if the offset parameter is not a valid, zero-based index into the data DOMString.
Raised if the node is read-only.
public void insertData(long offset, String arg) throws DOMException;
// 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.
The offset of the beginning of the replacement region.
The number of characters to replace. If offset + count is >= the length attribute, everything beyond the offset character position is replaced.
The replacement string.
The replaceData operation is the equivalent of the following code fragment:
cdNode.deleteData(offset, count); cdNode.insertData(offset, arg);
Raised if the offset parameter is not a valid, zero-based index into the data DOMString.
Raised if the node is read-only.
public void replaceData(long offset, long count, String arg) throws DOMException;
// 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.
Zero-based, starting offset of the substring to return. A valid offset must be >= 0 and < the length attribute of the node.
Count of characters to return.
Raised if the given offset is < 0, >= the length attribute, or if the count parameter is negative.
Raised if the value that would be returned is too large to be contained by a DOMString type in the given implementation.
public String substringData(unsigned long offset, unsigned long count) throws DOMException;
// 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.
|
// 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.
public DocumentType getDoctype( );
// 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.
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.
public DOMImplementation getImplementation( );
// 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.
The name of the XML attribute.
The new Attr object.
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.
public Attr createAttribute(String name) throws DOMException;
// 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.
The URI associated with the namespace prefix in the qualifiedName parameter.
The name of the attribute to instantiate; includes the namespace prefix associated with the namespace URI given in the namespaceURI parameter.
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 |
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.
Raised if the qualifiedName is malformed or has a prefix but no namespaceURI, or if the reserved xml namespace prefix was used incorrectly.
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 >.
The text contained by the new CDATASection object.
Occurs if you try to call this method on an HTML document.
public CDATASection createCDATASection(String data) throws DOMException;
// 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.
The comment text.
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.
public Comment createComment(String data);
// 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.
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.
The XML name used to create the new Element node. This name is assigned to the nodeName attribute of the resulting Element node.
The new Element object.
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.
public Element createElement(String tagName) throws DOMException;
// 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.
The URI associated with the namespace prefix in the qualifiedName parameter.
The name of the element to instantiate, including the namespace prefix associated with the namespace URI given in the namespaceURI parameter.
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 |
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.
Raised if the qualifiedName is malformed, has a prefix but no namespaceURI, or if the reserved xml namespace prefix was used incorrectly.
public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;
createEntityReference: name |
This creates an EntityReference object.
The name of the XML entity to be referenced. The name must match an XML entity declaration that is valid in the current document.
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.
Generated if you attempted to create an entity reference using an HTML document.
public EntityReference createEntityReference(String name) throws DOMException;
// 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.
The target name of the processing instruction. This name identifies the application that will interpret the data portion of the instruction.
The application-specific data for the resulting ProcessingInstruction node.
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.
Generated if you attempt to create a ProcessingInstruction using an HTML document.
public ProcessingInstruction createProcessingInstruction(String target, String data) throws DOMException;
// 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.
The string that will be the contents of the new node.
public Text createTextNode(String data);
// 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.
|
The unique ID value for the desired element.
A single Element object that has the requested ID attribute or null, if no match is found.
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.
The name of the tag to use as a filter. The special name * matches any tag.
public NodeList getElementsByTagName(String tagName);
// 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.
The namespace URI of the elements to be matched. The special * value matches any namespace.
The local name part of the elements to be matched. The special value * matches any local name.
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.
The node duplicated for use in the current document hierarchy.
Whether to copy the single node given or the entire subtree of its children. For details, see the previous table.
Thrown if an attempt is made to import an unsupported Node type, such as a Document node.
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.
public NamedNodeMap getEntities( );
// 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.
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.
public String getName( );
// 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.
public NamedNodeMap getNotations( );
// 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.
public String getPublicId( );
systemId: DOMString |
The system identifier (URI) of this document's external subset. Read-only.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
public static final short INVALID_STATE_ERR = 11;
SYNTAX_ERR [unsigned short, value: 12]2 |
An invalid or illegal string was specified.
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.
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.
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.
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.
// 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.
The namespace URI used to create the top-level document element. Can be null if no namespace is used.
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.
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.
Indicates that the qualifiedName parameter has a malformed XML identifier.
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.
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.
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.
The qualified name of the document type to be created.
The external subset's public identifier.
The system identifier (URI) of the external subset to be created.
A new DocumentType object with the ownerDocument attribute set to null.
Indicates that the qualifiedName parameter has a malformed XML identifier.
Raised if the qualified name is malformed.
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.
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:
Supports DOM Level 1.0 or 2.0 Core objects.
Supports DOM Level 1.0 or 2.0 HTML objects.
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.
public boolean hasFeature(String feature, String version);
// Make sure that DOM Level 1 XML is supported if (!di.hasFeature("XML", "1.0")) { return null; }
|
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:
tagName: DOMString |
The XML tag name from the original document.
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) |
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.
public String getAttribute(String name);
// 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.
The namespace URI of the attribute to return.
The local name portion of the qualified attribute name to return.
Returns an empty string if no attribute is set and if no default attribute value was specified in the DTD.
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.
Name of the attribute to retrieve.
public Attr getAttributeNode(String name);
// 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.
Namespace URI of the target attribute.
Local name of the target attribute. The local name is the part of the name to the right of the : in a qualified name.
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.
The name of the tag to use as a filter. The special name * matches any tag.
public NodeList getElementsByTagName(String name);
// 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.
The namespace URI of elements to be matched. The special * value matches any namespace.
The local name part of elements to be matched. The special value * matches any local name.
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.
The name of the attribute to be identified.
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.
The namespace URI of the attribute to be identified.
The local name of the attribute to be identified.
public boolean hasAttribute(String namespaceURI, String localName);
normalize |
Traverses the subtree of the current Element, combining adjacent Text nodes into a single node.
|
public void normalize( );
// 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.
Name of the attribute to remove.
Raised if the element is read-only.
public void removeAttribute(String name) throws DOMException;
// 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.
Namespace URI of the target attribute.
Local name part of the target attribute. The local name is the part to the right of the final : in a qualified name.
Raised if the element is read-only.
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.
The attribute node to remove.
Raised if the node is read-only.
Raised if no attribute name matching the oldAttr parameter is found in the map.
public Attr removeAttributeNode(Attr oldAttr) throws DOMException;
// 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.
The attribute name to set or modify.
The new attribute value.
Indicates that the attribute name you passed in doesn't represent a valid XML attribute name.
Raised if the element is read-only.
public void setAttribute(String name, String value) throws DOMException;
// 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.
The namespace URI of the attribute value to set.
The qualified name (including namespace prefix) of the new value to set.
The new attribute value.
Indicates that the attribute name you passed in doesn't represent a valid XML attribute name.
Raised if the element is read-only.
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.
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.
The new Attr object to set.
Raised if the newAttr node was created in a document different than the parent node.
Raised if the new parent node is read-only.
Raised if another Element already uses the new Attr node. Each element must have a distinct Attr object.
public Attr setAttributeNode(Attr newAttr) throws DOMException;
// 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.
The new Attr object to set.
Raised if the newAttr node was created in a different document than the parent node.
Raised if the new parent node is read-only.
Raised if another Element already uses the newAttr node. Each element must have a unique Attr object.
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:
notationName: |
If this entity is unparsed, the entity's notation name. For parsed entities, this attribute is null.
public String getNotationName( );
// 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.
public String getPublicId( );
// 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.
public String getSystemId( );
// 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:
length: unsigned long |
The total number of Node objects in the list.
public long getLength( );
// Iterate over the attribute list for (int i = 0; i < nnm.getLength( ); i++) { ... }
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.
Name of the node to retrieve.
public Node getNamedItem(String name);
// 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.
Namespace URI of the node to retrieve.
Local name of the node to retrieve.
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.
Zero-based index of the list of the node to return.
public Node item(long index);
// 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.
The nodeName value of the node to be removed.
Raised if no node matching the name parameter is found in the map.
public Node removeNamedItem(String name) throws DOMException;
// 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.
Namespace URI of the node to retrieve.
Local name of the node to retrieve.
Raised if no node matching the namespaceURI and localName parameter is found in the map.
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.
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.
Raised if a document different than the creator of the target NamedNodeMap created the arg node.
Raised if the NamedNodeMap is read-only.
Raised if the arg node is an Attr node that is already in use by another element's attributes map.
public Node setNamedItem(Node arg) throws DOMException;
// 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.
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.
Raised if a document different than the creator of the target NamedNodeMap created the arg node.
Raised if the NamedNodeMap is read-only.
Raised if the arg node is an Attr node already in use by another element's attributes map.
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.
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.
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.
public NodeList getChildNodes( );
// 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 ReferencesThroughout 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.
public Node getFirstChild( );
// 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.
public Node getLastChild( );
// 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.
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.
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.
public Node getNextSibling( );
// 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 |
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.
public short getNodeType( );
// 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 |
Indicates the nodeValue attribute is read-only for this DOM object type.
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.
public String getNodeValue( ) throws DOMException; public void setNodeValue(String nodeValue) throws DOMException;
// 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.
public Document getOwnerDocument( );
// 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.
Node getParentNode( );
// 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.
Raised if the prefix includes an illegal character.
Indicates that the prefix attribute is read-only for this DOM object type.
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.
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.
public Node getPreviousSibling( );
// 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) |
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.
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.
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).
Raised if the newchild node is created in a different document than that of the new parent node.
Raised if the new parent node is read-only.
public Node appendChild(Node newChild) throws DOMException;
// 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.
If true, child nodes are copied to the cloned node. If false, only the original node is copied.
public Node cloneNode(boolean deep);
// 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.
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.
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.
The new node to insert.
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.
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).
Raised if the newchild node was created in a document different than that of the new parent node.
Raised if the new parent node is read-only.
Raised if the node pointed to by refchild is not a child of the node performing the insert.
public Node insertBefore(Node newChild, Node refChild) throws DOMException;
// 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.
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.
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.
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.
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.
The node to be removed.
Raised if the parent node is read-only.
Raised if the oldchild node is not a child of this node.
public Node removeChild(Node oldChild) throws DOMException;
// 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.
The node to be inserted.
The node being replaced.
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).
Raised if the newchild node was created in a different document than the new parent node.
Raised if the new parent node is read-only.
Raised if the node pointed to by oldchild is not a child of the node performing the replacement.
public Node replaceChild(Node newChild, Node oldChild) throws DOMException;
// 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.
// 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( )); } }
The NodeList interface defines one attribute:
length: unsigned long |
The total number of Node objects in the list.
public long getLength( );
NodeList (continued) |
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.
Zero-based index into the list of the Node to return.
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.
// Add an application-specific processing instruction ProcessingInstruction pi = doc.createProcessingInstruction("my_app", "action=\"save\"");
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 ?>.
Raised if the node is read-only.
public String getData( ); public void setData(String data) throws DOMException;
// 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.
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>
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.
Zero-based offset where the split occurs.
Raised if the offset given is < 0 and >= the length attribute.
Raised if the element is read-only.
public Text splitText(long offset) throws DOMException;
// Make one Text node long = doc.createTextNode("This text is split."); // and split it Text ndSplit = ndText.splitText(9);
|
![]() | CONTENTS | ![]() |