Attr |
The Attr interface represents the value assigned to an attribute of an XML element. The parentNode , previousSibling , and nextSibling of an Attr are always 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.
An Attr object can have EntityReference objects as children. The value attribute provides the expanded DOMString representation of this attribute.
//Get the element's size attribute as an Attr object Attr attrName = elem.getAttributeNode("size");
The following attributes are defined for the Attr object:
isId: boolean (3) |
Returns true if this attribute contains a unique identifier for the parent element node. Attributes are tagged as identifiers by the DTD, the schema, or by using one of the setIdAttribute( ) methods of the Element interface. Read-only.
public boolean isId( );
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: Element (2) |
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( );
schemaTypeInfo: TypeInfo (3) |
This property provides a link to any type information that may be available for this attribute, based the DTD or Schema associated with the parent document. May be unreliable if the node has been moved from one element to another. Read-only.
public TypeInfo getSchemaTypeInfo( );
specified: boolean |
This indicates whether this attribute was explicitly set in the XML source for the parent element or is a default value specified in the DTD or schema. 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( )); }
The Attr object has no methods.
CDATASection |
The CDATASection interface contains the unparsed, unescaped data contained within CDATA blocks in an XML document. Although 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. Although 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 = 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 0 <= index < length . This value can be 0 since it is possible to have an empty CharacterData node. 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.");
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 remainderstarting 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 = doc.createTextNode("The truth is not out there."); // change of heart ndCD.deleteData(12, 4); System.out.println(ndCD.getData( ));
insertData: offset, 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 = 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 specified 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 = 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. Although 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 = 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 document type declaration for this document. If no DOCTYPE declaration was in the document, this property is null . Prior to DOM Level 3, the DocumentType node associated with a document was immutable and could not be created directly. In Level 3 implementations, the doctype attribute is a shortcut to the DocumentType node that is currently linked into the document node hierarchy. 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.");
documentURI: DOMString (3) |
The location of the document, or null if the document was created using the createDocument( ) method of the DOMImplementation interface. No lexical checking of the URI itself is done during the set operation.
public String getDocumentURI( ); public void setDocumentURI(string documentURI);
domConfig: DOMConfiguration (3) |
Returns the DOMConfiguration object instance associated with this document. The DOMConfiguration controls the operation of the normalizeDocument( ) method. See the DOMConfiguration interface for a detailed list of parameters and their effects on the behavior of normalizeDocument( ) . Read-only.
public DOMConfiguration getDomConfig( );
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; }
inputEncoding: DOMString (3) |
Gives the character encoding detected when the document was parsed. See Chapter 5 for more information about character encodings. Is null when encoding is not known. Read-only.
public String getInputEncoding( );
strictErrorChecking: boolean (3) |
When set to false , DOM implementations are free to ignore error conditions (such as invalid characters in identifiers) that would ordinarily raise a DOMException . Although exceptions will not be raised, the behavior of the implementation after encountering an error is undefined. The default value of this attribute is true .
public boolean getStrictErrorChecking( ); public void setStrictErrorChecking(boolean strictErrorChecking);
xmlEncoding: DOMString (3) |
Returns the character encoding specified in the encoding pseudo-attribute of the XML declaration from the original document. See Chapter 5 for more information about character encodings. Is null when encoding is not known. Read-only.
public String getXmlEncoding( );
xmlStandalone: boolean (3) |
Returns the value of the standalone pseudo-attribute of the XML declaration from the original document. Returns false when not specified in the declaration. Note that this value returns the standalone value from the original declaration and may not be accurate.
public boolean getXmlStandalone( ); public void setXmlStandalone(boolean xmlStandalone) throws DOMException;
xmlVersion: DOMString (3) |
Returns the value of the version pseudo-attribute of the XML declaration of the document. For documents without an XML declaration, this value defaults to " 1.0 ". Changing this value to " 1.1 " changes how methods that check for invalid characters in XML names ( createElement( ) , setAttribute( ) , etc.) behave, per the XML 1.1 standard. For more information on the differences between XML 1.0 and 1.1, see Chapter 2 and Chapter 21.
public String getXmlVersion( ); public void setXmlVersion(string xmlVersion) throws DOMException;
The following methods are defined for the Document object:
adoptNode: adoptNode, source (3) |
Similar to importNode( ) , this method is used to migrate a DOM Node from one Document instance to another. The source node is removed from the DOM tree of its parent document and prepared to be inserted into the adopting document, unlike the importNode() method which creates a copy of the source node and leaves the original in place. The following table explains the behavior of this method for the individual node types:
Node type | Result |
---|---|
ATTRIBUTE_NODE | Adopts the source attribute and all its children. The ownerElement attribute is set to null , and the specified flag is set to true . |
DOCUMENT_FRAGMENT_NODE | Adopts the DocumentFragment node along with all of its child nodes. |
DOCUMENT_NODE | Cannot be adopted. |
DOCUMENT_TYPE_NODE | Cannot be adopted. |
ELEMENT_NODE | Adopts the element as well as all child nodes. Adopts the attribute nodes that have their specified flag set, and may insert additional attributes based on the DTD or schema of the target document. |
ENTITY_NODE | Cannot be adopted. |
ENTITY_REFERENCE_NODE | Adopts only the EntityReference node. Its value, if any, is taken from the DTD of the document doing the import. |
NOTATION_NODE | Cannot be adopted. |
PROCESSING_INSTRUCTION_ NODE , TEXT_NODE, CDATA_SECTION_NODE, COMMENT_NODE | All adopted without restrictions. |
Since the newly adopted node was not created by the target document, it is possible that the names of elements, attributes, etc., may not conform to the XML version of the new document (see the xmlVersion attribute). Consider using the normalizeDocument( ) method to ensure that adopted nodes are well-formed.
The node to be adopted.
Thrown if an attempt is made to import an unsupported Node type, such as a Document node.
Thrown if the source node is read-only.
public Node adoptNode(Node source) throws DOMException;
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( ) is not a valid XML name. See Chapter 2 for the XML restrictions on name construction.
public Node adoptNode(Node source) throws DOMException;
createAttributeNS: namespaceURI, qualifiedName (2) |
This method serves the same purpose as the createAttribute method, but is used when the attribute is in a namespace.
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( ) is not 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.
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 the NOT_SUPPORTED_ERR [unsigned short, value: 9] reference 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( ) is not a legal 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, qualifiedName (2) |
This method serves the same purpose as the createElement method but is used when the element is in a namespace.
The namespace URI.
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( ) is not a legal 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( ) is not a legal 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 and can't be used by an application.
The target name of the processing instruction.
The application-specific data for the resulting ProcessingInstruction node.
Indicates that the name you passed in to createProcessingInstruction is not a legal 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: elementID (2) |
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, localName (2) |
Like the getElementsByTagName( ) method, this method returns a list of Element nodes (a NodeList object) that have the criteria given namespaceURI and localName . 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.
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, deep (2) |
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, as described in this table:
Node type | Result | Effect of deep flag |
---|---|---|
ATTRIBUTE_NODE | Adopts 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 | Adopts the attribute nodes with the specified flag set to the new element. | Recursively copies all the source element's children. |
ENTITY_NODE | Adopts the publicId , systemId , and notationName attributes. | Recursively copies all of the Entity node's children. |
ENTITY_REFERENCE_NODE | Adopts 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 the DocumentType interface is read-only in Level 2, it cannot be included in the target document. | None. |
PROCESSING_INSTRUCTION_NODE | Adopts the target and data values. | None. |
TEXT_NODE, CDATA_SECTION_NODE, COMMENT_NODE | Adopts 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;
normalizeDocument( ) (3) |
This method performs the equivalent of a load and save operation, returning the document to its "normal" form. This includes coalescing Text nodes, possibly expanding EntityReference nodes, etc. The types of operations that occur during the normalization process are controlled by the values of the parameters in the DOMConfiguration object (see the domConfig attribute). For a list of the standard configuration parameters available, see the DOMConfiguration interface.
public void normalizeDocument( );
renameNode: n, namespaceURI, qualifiedName (3) |
Allows Element and Attr type nodes to be renamed . Whenever possible, the nodeName attribute of the target Node is modified directly. If simply changing the name is not possible, a node is created with the new name and the child nodes of the old node are moved to the new node. If the node is an Element node, renaming it will cause it to lose the default attributes of the old node name and gain those corresponding to its new name.
The node to rename.
The namespace URI for the renamed node.
The new qualified name for the node.
Thrown if the target nodeType is not ELEMENT_NODE or ATTRIBUTE_NODE , or if the implementation does not support renaming the documentElement .
Thrown if the new qualified name is not a name according to the contents of the xmlVersion attribute.
Thrown if an attempt is made to rename a node from a different document.
Raised if the qualifiedName is malformed or has a prefix but no namespaceURI , or if the reserved xml namespace prefix was used incorrectly.
public Node renameNode(Node n, String namespaceURI, String qualifiedName) 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-balanced 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 subtrees that appear at the same level of the tree to be copied:
<document> <parent> <child_1></child_1> <child_2></child_2> </parent> <parent> </parent> </document>
If the user decides to copy the two child nodes to the clipboard, the DOM application would do the following:
Create a DocumentFragment object.
Attach copies of the child nodes to the new object using the cloneNode( ) and appendChild( ) methods.
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.
// 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( );
The DocumentType object has no methods.
DOMConfiguration (3) |
This interface is accessible through the domConfig attribute of a given DOM Document object. This object is essentially a list of configuration options that affect how documents are loaded, saved, and validated by the DOM implementation. By using the setParameter( ) method to modify these options, it is possible to change the behavior of the Document.normalize( ) method. For example, by setting the " entities " parameter to false , subsequent calls to the Document.normalize( ) method would cause all EntityReference nodes to be replaced with their replacement text and coalesced with adjacent Text nodes. The following table lists the valid parameters for the DOMConfiguration object:
Parameter name | Value | Meaning |
---|---|---|
canonical-form | true | Canonicalize the document per the Canonical XML specification. Duplicate namespace declarations are removed, and other changes are made to reduce the document to its simplest possible form. Setting this parameter to true automatically sets the following parameters: cdata-sections : false element-content-whitespace : true entities : false namespace-declarations : true namespaces : true normalize-characters : false well-formed : true |
false [1] | Do not canonicalize. | |
cdata-sections | true [1] | Keep CDataSection nodes intact. |
false | Transform CDataSection nodes into Text nodes and coalesce redundant Text nodes as necessary. | |
check-character-normalization | true | Check that the characters in the document are fully normalized per Appendix B of the XML 1.1 specification. |
false [1] | Do not check for character normalization. | |
comments | true [1] | Keep Comment nodes in document. |
false | Discard Comment nodes. | |
datatype-normalization | true | Expose the normalized value of a node (i.e., strings with collapsed whitespace) within the tree, per the information from the schema used for validation. For this to occur, the validate parameter must also be set to true . |
false [1] | Do not perform schema normalization. | |
element-content-whitespace | true [1] | Keep all whitespace from the original document. |
false | Discard Text nodes that contain element whitespace . See the Text.isElementContentWhitespace attribute for more information. | |
entities | true [1] | Keep EntityReference nodes in the document. |
false | Replace EntityReference nodes with their expansions as Text nodes (which will be coalesced as necessary). | |
error-handler | DOMError-Handler | This property may be set to an object instance that implements the DOMErrorHandler interface. The DOMErrorHandler.handleError( ) method will then be called if errors occur during document operations. |
infoset | true | This parameter is a shortcut to force the DOM processor to conform to the XML Information Set specification. Setting this parameter to true automatically sets the following parameters: cdata-sections : false comments : true datatype-normalization : false element-content-whitespace : true entities : false namespace-declarations : true namespaces : true validate-if-schema : false well-formed : true |
false | Setting the infoset parameter to false has no effect. | |
namespaces | true [1] | Minimizes the number of namespace declarations throughout the document by assigning elements and attributes to the " nearest " namespace declaration that matches their namespace URI. |
false | No namespace declaration processing is done. | |
namespace-declarations | true [1] | Note that this parameter is only effective if the namespaces parameter is set to true . Include all namespace declaration attributes as Attr nodes within the document. |
false | Discard namespace declaration nodes. | |
normalize-characters | true | Fully normalize the characters in the document per Appendix B of the XML 1.1 Recommendation. |
false [1] | Do not perform character normalization. | |
schema-location | DOMString | A space-separated list of URIs of schemas against which the document will be validated. This parameter works in conjunction with the schema-type parameter. The value of this parameter takes precedence over the schema information specified in the document. |
schema-type | DOMString | An absolute URI representing what type of schema documents are referenced by the schema-location parameter. The two schema type URIs given in the DOM specification are: XML Schema: http://www.w3.org/2001/XMLSchema XML DTD: http://www.w3.org/TR/REC-xml |
split-cdata-sections | true [1] | Automatically splits a CDATA section whose text value contains the ]]> termination marker. The termination marker code will be converted to text and another CDATA section created to follow the new Text node. |
false | Raise an error if a CDATASection contains unrepresentable content. | |
validate | true | Require that the document be validated against a schema during the Document.normalization( ) process. The schema may come from the schema-location parameter or from within the document itself. |
false [1] | Do not validate, including the internal subset, unless the validate-if-schema parameter is set to true . | |
validate-if-schema | true | Validate only if a schema can be found for the document element. |
false [1] | Do not validate, unless the validate parameter is set to true . | |
well-formed | true [1] | Ensure that the document is well-formed. This includes checking the content of Attr , Element , Comment , Text , CDataSection , and ProcessingInstruction nodes for characters that could not be present in a well-formed XML document. For example, the ]]> CDATA termination sequence cannot be present in the text value of a CDataSection node. |
false | Do not enforce character value restrictions within the DOM nodes. This may result in a document that will not be well-formed when saved and reparsed. |
[1] Indicates the parameter's default value. Parameters without a default value are optional.
The DOMConfiguration object contains the following attributes:
parameterNames: DOMStringList (3) |
Returns the list of parameters supported by the DOMConfiguration object. May include parameters that are not part of the DOM Recommendation. Read-only.
public DOMStringList getParameterNames( );
The DOMConfiguration object defines the following methods:
canSetParameter: name, value (3) |
Returns true if the name parameter could accept the value given. Essentially the same as calling setParameter( ) without actually modifying the value of the parameter.
The name of a valid parameter (from the parameterNames list) to verify.
The potential value to verify.
public boolean canSetParameter(String name, Object value);
getParameter: name (3) |
Returns the value of the parameter given, if it is known. The return value is of the type DOMUserData , and is null if the specified parameter has no value associated or is not recognized.
The name of a valid parameter (from the parameterNames list) to verify.
Raised if the given parameter name is not recognized.
public Object getParameter(String name) throws DOMException;
setParameter: name, value (3) |
Attempts to set the named parameter to the value given.
The name of a valid parameter (from the parameterNames list) to set.
The new value of the parameter.
Raised if the given parameter name is not recognized.
Raised if the given parameter name is recognized but not supported.
Raised if the value for this parameter is incompatible with the expected type (e.g., attempting to set the error-handler parameter to an object that doesn't implement the DOMErrorHandler interface).
public void setParameter(String name, Object value) throws DOMException;
The DOMConfiguration object has no methods.
DOMError (3) |
This interface defines an object that will contain information regarding errors that might occur during DOM operations. It is used as a parameter to the DOMErrorHandler.handleError() callback method.
The DOMError object contains the following attributes:
location: DOMLocator (3) |
Contains information regarding the location of the error within the original XML document as well as within the DOM tree. Read-only.
public DOMLocator getLocation( );
message: DOMString (3) |
A message generated by the DOM implementation describing the error. Read-only.
public String getMessage( );
relatedData: DOMObject (3) |
Based on the type attribute, this attribute will most likely contain a reference to the DOM Node object that caused the error.
public Object getRelatedData( )
relatedException: DOMObject (3) |
If the error is the result of a platform-dependent exception, this attribute will contain a reference to the exception object in question.
public Object getRelatedException( )
severity: unsigned short (3) |
This attribute indicates the severity of the error, which will be one of the constants from the following table:
Severity constant | Value | Meaning |
---|---|---|
SEVERITY_WARNING | 1 | This is an "informational" error, and DOM processing may proceed normally. |
SEVERITY_ERROR | 2 | This is a possibly recoverable error (such as a schema validation problem in an otherwise well-formed document). |
SEVERITY_FATAL_ERROR | 3 | An unrecoverable error (such as a well- formedness problem) has occurred. |
public short getSeverity( )
type: DOMString (3) |
The value of the type attribute determines what type of object reference will appear in the relatedData attribute.
public String getType( )
The DOMError object has no methods.
DOMErrorHandler (3) |
This is a callback interface that allows DOM programmers to register an object to receive notifications when errors occur during DOM operations. The DOMConfiguration.setParameter( ) method is used with the error-handler parameter name to register a DOMErrorHandler for a given implementation.
The DOMErrorHandler object has no attributes.
The following method is defined for this object:
handleError: error (3) |
This is the callback method that is invoked by the DOM when an error occurs. Programmers using the DOM are responsible for implementing this method, processing errors, and determining whether processing should continue or be aborted. If this method returns true , processing will continue (unless an error of SEVERITY_FATAL_ERROR has occurred). If it returns false , processing will halt.
The object that describes the error.
public boolean handleError(DOMError error);
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.
public static final short WRONG_DOCUMENT_ERR = 4;
INVALID_CHARACTER_ERR [unsigned short, value: 5] |
An invalid character was used in a namee.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 read-only node.
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 the specific implementation of the DOM did not 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;
VALIDATION_ERR [unsigned short, value: 16] (3) |
An attempted modification to the document tree would result in a validity error.
public static final short VALIDITY_ERR = 16;
TYPE_MISMATCH_ERR [unsigned short, value: 17] (3) |
Raised if the type of a parameter is not compatible with the expected type.
public static final short TYPE_MISMATCH_ERR = 17;
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 has no attributes.
The DOMImplementation object defines the following methods:
createDocument: namespaceURI, qualifiedName, doctype (2) |
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, systemId (2) |
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;
getFeature: feature, version (3) |
Provides a nonbinding-specific way to retrieve an object instance that implements a specific version of a given feature. Primarily used to access features beyond the scope of the DOM Core.
The package name of the feature to retrieve.
The DOM version level of the specified feature to retrieve.
Returns an object that implements the APIs for the specified features, or null if no implementation is available.
public Object getFeature(String feature, String version);
hasFeature: feature, version |
Tests to see if the DOM implementation supports a specific version of a named feature package.
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 version number is specified, the function returns true if any version is supported.
Returns true if the particular version of the specified feature is available; otherwise, it returns false .
public boolean hasFeature(String feature, String version);
// Make sure that DOM Level 1 XML is supported if (!di.hasFeature("XML", "1.0")) { return null; }
|
DOMImplementationRegistry (3) |
One of the concepts introduced in the Level 3 Core is that of "bootstrapping" a DOM implementation. Prior to Level 3, some language- and implementation-specific code was needed to initially create a DOMImplementation that could be used to create documents and gain access to DOM functionality. The DOMImplementationRegistry object has no formal IDL specification within the DOM recommendation, but every implementation of the Level 3 Core is required to provide an object that implements two methods: getDOMImplementation( ) and getDOMImplementationList( ) . These methods are then used to locate a DOMImplementation object that supports the required features for the application.
DOMImplementationSource (3) |
This interface supplies an ordered list of DOMImplementation objects that can be accessed via a zero-based index.
The DOMImplementationSource object has no attributes.
The following methods are defined for this object:
getDOMImplementation: features (3) |
Used to retrieve a DOMImplementation object that matches the space-separated list of features (and optional version numbers) provided. DOM implementers are free to provide multiple versions of the various DOM components , which developers can query at runtime using this method. Most of the available features are beyond the scope of this book; however, it is possible to request a specific version of XML support by passing in a features string such as the following: " XML 3.0 ". This string would request that a DOMImplementation object that supports Version 3.0 of the XML Core be returned. If no matching implementation is available, the method returns null .
The space-separated list of requested features and versions.
public DOMImplementation getDOMImplementation(String features);
getDOMImplementationList: features (3) |
Used to retrieve a list of DOMImplementation objects that matches the space-separated list of features (and optional version numbers) provided. The list is returned as a DOMImplementationList . For more information on the construction of the features argument, see the getDOMImplementation( ) method.
The space-separated list of requested features and versions.
public DOMImplementationList getDOMImplementation(String features);
DOMLocator (3) |
This interface describes an object that can identify a specific location within a document that is being processed by a DOM implementation.
The DOMLocator object contains the following attributes:
byteOffset: long (3) |
The byte offset into the input source, or -1 if no byte offset is available. Read-only.
public int getByteOffset( );
columnNumber: long( 3) |
The column number within the line of the input source, or -1 if no column number is available. Read-only.
public int getColumnNumber( );
lineNumber: long (3) |
The line number within the line of the input source, or -1 if no line number is available. Read-only.
public int getLineNumber( );
relatedNode: Node (3) |
This attribute contains a reference to the DOM Node object that corresponds to the document location in question. Read-only.
public Node getRelatedNode( )
uri: DOMString (3) |
The URI of the source document if it is available; otherwise, it is null . Read-only.
public String getUri( );
utf16Offset: long (3) |
Similar to the byte offset attribute, but instead of returning an absolute byte reference, it returns a UTF character offset, per the Unicode specification. See Chapter 5 for more information about character encodings and Unicode. Read-only.
public int getUtf16Offset( );
The DOMLocator object has no methods.
DOMObject (3) |
Starting with DOM Level 3, some methods either accept or return a reference to a language-specific object. The DOMObject type provides a generic placeholder to represent these objects in the DOM IDL. For Java and ECMAScript, this type is bound to the Object type.
DOMString |
The DOMString type serves as a generic placeholder within the DOM IDL for the native string handling type for a given implementation language. For example, within the Java binding, the DOMString type maps to the java.lang.String type.
DOMStringList (3) |
This interface supplies a read-only, ordered list of DOMString objects that can be accessed via a zero-based index.
The DOMStringList object contains the following attribute:
length: unsigned long (3) |
Gives the number of DOMString objects in the list. Read-only.
public int getLength( );
The following methods are defined for this object:
contains: str (3) |
Returns true if the given string is contained in the list; otherwise, it returns false .
The string value to locate.
public boolean contains(String str);
item: index (3) |
Used to retrieve strings from the list. Valid values for the index argument are 0 through length - 1. If an invalid index is provided, this method returns null .
The index of the string to retrieve.
public String item(int index);
DOMUserData(3) |
The new Node.getUserData() and Node.setUserData( ) methods are intended to allow the programmer to store application-specific information within the DOM tree. The DOMUserData type provides a generic placeholder for use within the DOM IDL descriptions. For Java and ECMAScript, this type is bound to the Object type.
Element |
The Element interface 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 contains the following attributes:
schemaTypeInfo: TypeInfo (3) |
This property provides a link to any type information that may be available for this element, based on the DTD or Schema associated with the parent document. Read-only.
public TypeInfo getSchemaTypeInfo( );
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.");
The following methods are defined for this object:
getAttribute: name |
Returns the attribute specified by the name parameter as a DOMString . See createElementNS: namespaceURI, qualifiedName (2) 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, localName (2) |
Returns an attribute as a DOMString , based on the namespace URI 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 with the given name. Returns a reference to the attribute object if it is found; otherwise, it is 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, localName (2) |
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, it 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, localName (2) |
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: name (2) |
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, localName (2) |
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 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, localName (2) |
Removes the attribute with the given namespace URI and local name 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, value (2) |
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 the namespace prefix) of the new value to set.
The new attribute value.
Indicates that the attribute name you passed in is not a legal 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: newAttr (2) |
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;
setIdAttribute: name, isId (3) |
This method provides a way to mark an attribute as a user-determined ID attribute. Although attributes that are marked as ID attributes using this method will show up in searches conducted using the Document.getElementById( ) method, it will not modify any of the type information provided by the Attr.schemaTypeInfo attribute. To mark namespace-aware attributes, use the setIdAttributeNS( ) method.
The attribute name to modify.
Set to true if the attribute is to be an ID attribute; otherwise, set to false .
Raised if the element is read-only.
Raised if no attribute matching the name parameter is found in the attributes collection.
public void setIdAttribute(String name, boolean isId) throws DOMException;
setIdAttributeNS: namespaceURI, localName, isId (3) |
This method provides a way to mark an attribute that belongs to a namespace as a user-determined ID attribute. Although attributes that are marked as ID attributes using this method will show up in searches conducted using the Document.getElementById() method, it will not modify any of the type information provided by the Attr.schemaTypeInfo attribute.
The namespace URI of the attribute to modify.
The local part of the name of the attribute to modify.
Set to true if the attribute is to be an ID attribute; otherwise, it is false .
Raised if the element is read-only.
Raised if no attribute matching the name parameter is found in the attributes collection.
public void setIdAttributeNS(String namespaceURI, String localName, boolean isId) throws DOMException;
setIdAttributeNode: idAttr, isId (3) |
This method provides a way to mark an attribute as a user-determined ID attribute. Although attributes that are marked as ID attributes using this method will show up in searches conducted using the Document.getElementById( ) method, it will not modify any of the type information provided by the Attr.schemaTypeInfo attribute. To mark namespace-aware attributes, use the setIdAttributeNS( ) method.
The attribute to modify.
Set to true if the attribute is to be an ID attribute; otherwise, set to false .
Raised if the element is read-only.
Raised if the specified attribute is not an attribute of the element in question.
public void setIdAttributeNode(Attr idAttr, boolean isId) 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:
inputEncoding: DOMString (3) |
Gives the character encoding detected at parse time for external parsed entities. See Chapter 5 for more information about character encodings. Is null for internal parsed entities or if the encoding is not known. Read-only.
public String getInputEncoding( );
notationName: DOMString |
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 given for this entity, or null if none was specified.
public String getPublicId( );
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( ); }
xmlEncoding: DOMString (3) |
Returns the character encoding specified in the encoding pseudo-attribute of the text declaration for an external parsed entity. See Chapter 5 for more information about character encodings. Is null if no text declaration is present. Read-only.
public String getXmlEncoding( );
xmlVersion: DOMString (3) |
Returns the value of the version pseudo-attribute of the text declaration of an external parsed entity. Is null if no text declaration is present. Read-only.
public String getXmlVersion( );
The Entity object has no methods.
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");
NameList (3) |
This interface supplies a read-only, ordered list names and namespace values that can be accessed via a zero-based index.
The NameList object contains the following attributes:
length: unsigned long (3) |
Gives the number of name/namespace pairs in the list. Read-only.
public int getLength( );
The following methods are defined for this object:
contains: str (3) |
Returns true if the name given by the str parameter is contained in the list; otherwise, it returns false .
The name value to locate.
public boolean contains(String str);
containsNS: namespaceURI, name (3) |
Returns true if the given name/namespace pair is contained in the list; otherwise, returns false .
The namespace URI of the name to locate.
The name value to locate.
public boolean containsNS(String namespaceURI, String name);
getName: index (3) |
Used to retrieve names from the list. Valid values for the index argument are 0 through length - 1. If an invalid index is provided, this method returns null .
The index of the name to retrieve.
public String getName(int index);
getNamespaceURI: index (3) |
Used to retrieve the namespace URI associated with a given name from the list. Valid values for the index argument are through length - 1. If an invalid index is provided or the name has no associated namespace URI, this method returns null .
The index of the name to retrieve.
public String getNamespaceURI(int index);
NamedNodeMap |
The NamedNodeMap interface provides a mechanism used to retrieve Node objects from a collection by name. Although 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++) { ... }
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, localName (2) |
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, localName (2) |
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: arg (2) |
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 pseudo-attributes 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, and methods are provided for inserting and removing nodes within 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( ) + "\""); } }
baseURI: DOMString (3) |
Returns the effective base URI for the node in question, or null if none is available. The base URI is the absolute URI that should be used to properly resolve relative links from within an XML document.
public String getBaseURI( );
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 hierarcy, 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 the node does not have children, 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: DOMString (2) |
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: DOMString (2) |
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 has 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, as listed in this table:
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 lists 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 . This table lists the values for the object types.
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 typesexcept 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: DOMString (2) |
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( )); } }
textContent: DOMString (3) |
This attribute provides a quick method to get and set the textual content of nodes within the document tree. When used to retrieve text, it returns the contents of all descendant Text nodes without any whitespace normalization. Markup nodes ( Attr , Element , and so forth) are ignored. When used to set text, it causes any child nodes to be removed and a single Text node to be created and linked in as the only child of the target node. The following table shows how the textContent attribute is constructed for the various node types:
Node type | Value |
---|---|
ELEMENT_NODE ATTRIBUTE_NODE ENTITY_NODE ENTITY_REFERENCE_NODE DOCUMENT_FRAGMENT_NODE | Combines the textContent of all child nodes, excluding nodes of type COMMENT_NODE and PROCESSING_INSTRUCTION_NODE , or an empty string if no child nodes |
TEXT_NODE CDATA_SECTION_NODE COMMENT_NODE PROCESSING_INSTRUCTION_NODE | Returns the same value as the nodeValue attribute |
DOCUMENT_NODE DOCUMENT_TYPE_NODE NOTATION_NODE | Returns null |
Thrown on set if node is read-only.
Thrown on get when length of text content would exceed the maximum allowable length of a DOMString on the implementation platform.
public String getTextContent( ); public void setTextContent(String textContent) throws DOMException
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);
compareDocumentPosition: other (3) |
Compares the relative position of the node on which the method is invoked with the position of the other node. The return value is a bit mask that indicates the relative position between the two nodes in document order. The following table lists the bit mask members and their meanings:
Constant name | Value | Meaning |
---|---|---|
DOCUMENT_POSITION_DISCONNECTED | 0x01 | The two nodes are disconnected (do not share a common container ancestor ) and cannot be compared. |
DOCUMENT_POSITION_PRECEDING | 0x02 | The other node precedes the target node within the document. |
DOCUMENT_POSITION_FOLLOWING | 0x04 | The other node follows the target node. |
DOCUMENT_POSITION_CONTAINS | 0x08 | The other node contains the target node. |
DOCUMENT_POSITION_CONTAINED_BY | 0x010 | The other node is contained by the target node. |
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | 0x020 | The relative positions are implementation-specific, such as in the case of disconnected nodes. |
The other node to use in the position comparison.
Raised if the two nodes are from incompatible DOM implementations and their relative positions cannot be determined.
public static final short DOCUMENT_POSITION_DISCONNECTED = 0x01; public static final short DOCUMENT_POSITION_PRECEDING = 0x02; public static final short DOCUMENT_POSITION_FOLLOWING = 0x04; public static final short DOCUMENT_POSITION_CONTAINS = 0x08; public static final short DOCUMENT_POSITION_CONTAINED_BY = 0x10; public static final short DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20; public short compareDocumentPosition(Node other) throws DOMException;
getFeature: feature, version (3) |
Provides a nonbinding-specific way to retrieve an object instance that implements a specific version of a given feature. Primarily used to access features beyond the scope of the DOM Core.
The package name of the feature to retrieve.
The DOM version level of the specified feature to retrieve.
Returns an object that implements the APIs for the specified features, or null if no implementation is available.
public Object getFeature(String feature, String version);
getUserData: key (3) |
This method is used to retrieve user-defined data from a node that was placed there using the setUserData( ) method. If no user data with the given key is found, the method returns null .
The unique key associated with the user data to retrieve.
public Object getUserData(String key);
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.
Raised if the DOM implementation in question doesn't support inserting DocumentType or Element nodes into a Document node.
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( ));
isDefaultNamespace: namespaceURI (3) |
This method returns true if the namespace URI given is the default namespace for this node, false if it is not.
The namespace URI to check against the default namespace URI.
public boolean isDefaultNamespace(String namespaceURI);
isEqualNode: arg (3) |
This method compares the node on which the method is invoked with the node referenced by the other parameter. The two nodes are considered to be equal if:
They are of the same type
The following attributes are equal: nodeName , localName , namespaceURI , prefix , nodeValue
The attributes maps are equal (contain the same number of nodes that are equal to one another)
The childNodes lists are equal (the child node trees are identical, and each child passes this equality test with its counterpart in the other tree)
For DocumentType nodes only: the publicId , systemId , internalSubset , entities , and notations attributes must be identical as well
The method returns true if the nodes pass all of the above tests; otherwise, it returns false .
The node to use in the comparison.
public boolean isEqualNode(Node arg);
isSameNode: other (3) |
This method returns true if the node on which the method is invoked and the node referred to by the other parameter refer to the same Node object, false if they do not.
The other node to use in the comparison.
public boolean isSameNode(Node other);
isSupported: feature, version (2) |
Checks to see if a particular DOM feature is available for this implementation. For more information about the feature names, see the appendData: arg method of the CharacterData 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 details of the appendData: arg method of the CharacterData object for a list of this parameter's valid values.
The version number of the feature to test. For example, 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);
lookupNamespaceURI: prefix (3) |
This method searches for the namespace URI associated with the given namespace prefix, starting with the node on which it is invoked. It then recursively searches parent nodes until the prefix is located. The return value is a DOMString containing the namespace URI associated with the prefix if it is found; otherwise, the method returns null .
The namespace prefix to be located.
public String lookupNamespaceURI(String prefix);
lookupPrefix: namespaceURI (3) |
This method searches for the namespace prefix assigned to the given namespace URI, starting with the node on which it is invoked; it then recursively searches parent nodes until a suitable prefix is located. The return value is a DOMString containing the prefix if it is found; otherwise, the method returns null . If more than one suitable prefix is found, the returned prefix is implementation-specific.
The namespace URI of the prefix to be located.
public String lookupPrefix(String namespaceURI);
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.
Could be raised if the Document node of a DOM implementation in question doesn't support removing DocumentType or Element nodes.
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.
Could be raised if the Document node of a DOM implementation in question doesn't support replacing DocumentType or Element nodes.
public Node replaceChild(Node newChild, Node oldChild) throws DOMException;
// Replace an old node with a new one ndOld.getParentNode( ).replaceChild(ndNew, ndOld);
setUserData: key, data, handler (3) |
The setUserData( ) method (in conjunction with the getUserData( ) method) provides a facility for attaching application-specific information to DOM nodes. By using distinct key values, it is possible to attach multiple user objects to a single DOM node. The information to be attached must conform to the DOMUserData type and may include a data handler object that implements the UserDataHandler interface.
The unique key to associate with the data parameter in the node's list of user data.
The user data to attach.
An object that will receive notification when various operations are performed on the DOM node in question.
public Object setUserData(String key, Object data, UserDataHandler handler);
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( );
The NodeList interface defines one method:
item:index |
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 }
ProcessingInstruction has no methods.
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.
The Text interface defines the following attributes:
wholeText: DOMString (3) |
This is a convenience attribute that returns all of the text from the target node as well as the text from adjacent Text nodes, in document order. For the purposes of this attribute, Text nodes are considered to be adjacent if they can be reached without exiting, entering, or skipping any of the following node types: Element , Comment , and ProcessingInstruction . Read-only.
public String getWholeText( );
isElementContentWhitespace: boolean (3) |
Returns true if the element contains only whitespace that XML validation has determined to be insignificant. Whitespace is insignificant if it does not belong to an element that has been declared to contain text or mixed content. Read-only.
public boolean isElementContentWhitespace( );
The following methods are defined for the Text interface:
replaceWholeText: content (3) |
This is a convenience method for replacing multiple adjacent text nodes with a single node that will contain the text passed in the content argument. The method returns a reference to the Text node that received the new content, or null if content contained a zero-length string.
New text content to be used for replacement.
Raised if the element is read-only.
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 = doc.createTextNode("This text is split."); // and split it Text ndSplit = ndText.splitText(9);
|
TypeInfo (3) |
Starting with the DOM Level 3, Element and Attr nodes include a schemaTypeInfo attribute that may reference a TypeInfo object. For valid XML documents, this object is used to provide information about the declared data type for a given element or attribute. Since the DOM is intended to be parser-independent, the contents of this object will vary depending on the type of schema validation that was performed (XML DTD, XML Schema, RELAX NG, and so forth). The DOM Level 3 Core specification includes detailed information about the significance of the typeName and typeNamespace attributes for both DTDs and XML Schemas.
The TypeInfo object contains the following attributes:
typeName: DOMString (3) |
Returns the declared type name of the element or attribute (varies depending on the validation method used). Returns null if the type name is unknown. Read-only.
public String getTypeName( );
typeNamespace: DOMString (3) |
Returns the namespace URI of the type given in by the typeName attribute. For example, an attribute validated against the type xs:date will have a namespace of http://www.w3.org/2001/XMLSchema . Read-only.
public String getTypeNamespace( );
The following method is defined for this object:
isDerivedFrom: typeNamespaceArg, typeNameArg, derivationMethod (3) |
This method provides the capability to determine the relationship between the target data type and another data type (given by the typeNameArg and typeNamespaceArg arguments). This method returns true if the target type is derived from the given data type via one of the methods passed in using the derivationMethod bitmask argument; otherwise, it returns false . Currently, this method is only defined for use with XML Schema validation. For more information on type derivation methods in XML Schema, see Chapter 17.
The namespace associated with the typeNameArg argument.
The type name to be compared with the target type.
A bitmask that restricts which types of derivation the method will recognize. The valid bitmask values are listed below:
Constant name | Value | Meaning |
---|---|---|
DERIVATION_RESTRICTION | 0x00000001 | The target type is derived from the other type by restricting its possible values (e.g., a positive integer is derived from a signed integer by restricting it to nonnegative values). |
DERIVATION_EXTENSION | 0x00000002 | The target type is derived from the other type by extending its possible values (e.g., a signed integer type would be an extension of an unsigned integer). |
DERIVATION_UNION | 0x00000004 | The target type is partially derived from the other type by its inclusion in a union. |
DERIVATION_LIST | 0x00000008 | The target type is a list of items of the other type. |
public boolean isDerivedFrom(String typeNamespaceArg, String typeNameArg, int derivationMethod);
UserDataHandler (3) |
The Node.setUserData( ) method provides the capability for the programmer to register a callback object that will be notified when various operations are performed on the node in question. These callback objects must implement this interface to receive those notifications.
The UserDataHandler interface has no attributes.
The following method is defined for this interface:
handle: operation, key, data, src, dst (3) |
This method is called whenever the Node object to which the parent UserDataHandler -derived object is attached is imported or cloned. This method is to be implemented by users of the DOM who wish to receive notifications when watched Node objects are manipulated.
|
The type of operation that occurred, based on the following values:
Constant name | Value | Meaning |
---|---|---|
NODE_CLONED | 1 | The watched node was cloned using Node.cloneNode() . |
NODE_IMPORTED | 2 | The watched node was imported using Document.importNode() . |
NODE_DELETED | 3 | The node was deleted, which is not necessarily reliable in environments that have no explicit delete operator (such as Java). |
NODE_RENAMED | 4 | The node was renamed using Document.renameNode( ) . |
NODE_ADOPTED | 5 | The watched node was adopted using Document.adoptNode() . |
The user-defined key from the Node.setUserData( ) method for which the handle( ) method is being called.
The user data corresponding to the key argument that was originally set using the Node.setUserData( ) method.
The node being cloned, adopted, imported, or renamed. This argument will be null if the node is being deleted.
The newly cloned or imported node, or null if no new node was created.
public boolean isDerivedFrom(String typeNamespaceArg, String typeNameArg, int derivationMethod) ;