XML technologies / XML / XML in a Nutshell / DOM reference / Object reference / Node

(Excerpt from “XML in a Nutshell” by Elliotte Rusty Harold & W. Scott Means)

The interface Node is the base interface of DOM: every component of a DOM tree derives from it. Its attributes apply to arbitrary node types, and its basic methods suffice to traverse and inspect the entire tree without casts. For example, the attribute attributes contains a list of the attributes of an Element object. The same attribute is valid for a node of type ProcessingInstruction, although it has no meaningful value there. (To access the pseudo-attributes of a processing instruction, your application must replace the processing instruction’s contents.)

The Node interface also provides methods for finding nodes, inserting them into the DOM tree and removing them. It enables a library of generic methods for manipulating a document fragment independently of a particular node type.

 

Attributes

The following attributes provide information about the position of the Node object within the DOM tree. All are read-only; methods are provided to insert nodes into and remove them from the document tree:

 

attributes: NamedNodeMap

This attribute is meaningful only for nodes of type Element: in that case, it contains a NamedNodeMap of Attr objects. In all other cases, its value is null.

Java binding
public NamedNodeMap getAttribute( );

Java example

// Gibt die Attribute eines Elements aus.
NamedNodeMap nnm = doc.getDocumentElement().getAttribute(  );

if (nnm != null) {

    for (int i = 0; i < nnm.getLength(  ); i++) {
        // Attributnamen und -wert ausgeben
        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 to use to resolve relative links correctly in an XML document.

Java binding
public String getBaseURI( );

 

childNodes: NodeList

Returns a NodeList containing a reference to every child of the Node object.

Java binding
public NodeList getChildNodes( );

Java example

// Gibt den im Element enthaltenen Text aus.
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(  ));
    }
}

Live tree references
At many points, DOM specifies a node list reflecting the document tree’s current state. These references are almost always live: changes to the document appear in the list, and vice versa.
Though often advantageous, this property can complicate work through multithreading or unexpected side effects: remember that the list you are using may change elsewhere. To reduce the likelihood of such elusive bugs, repeatedly reread values such as the length of a NodeList or NamedNodeMap rather than storing them in a local variable.

 

firstChild: Node

Contains a pointer to the node’s first child in the list. If the node has no children, the value is null.

Java binding
public Node getFirstChild( );

Java example

// Ausgabe der Typen aller Kindknoten des aktuellen Elements
for (Node nd = ndDump.getFirstChild(  ); nd != null;
     nd = nd.getNextSibling(  )) {
    if (nd.getNodeValue(  ) != null) {
        System.out.println(nd.getNodeValue(  ));
    }
}

 

lastChild: Node

Contains a pointer to the node’s first child in the list. If the node has no children, the value is null.

Java binding
public Node getLastChild( );

Java example

// Ausgabe der Typen aller Kindknoten des aktuellen Elements in umgekehrter Reihenfolge
for (Node nd = ndDump.getLastChild(  ); nd != null;
     nd = nd.getPreviousSibling(  )) {
    if (nd.getNodeValue(  ) != null) {
        System.out.println(nd.getNodeValue(  ));
    }
}

 

localName: DOMString (2)

Contains the local portion of the fully qualified node name, the suffix to the right of : in a name with a namespace.

Java binding
public String getLocalName( );

 

namespaceURI: DOMString (2)

The namespace URI set when the Node object was created, or null otherwise. Thus the value is null if the node was created with a create NodeType ( ) method rather than a create NodeTypeNS ( ) method.

Java binding
public String getNamespaceURI( );

 

nextSibling: Node

Returns the next node in the sibling list. If there are no more siblings, meaning the current node is last, nextSibling returns null.

Java binding
public Node getNextSibling( );

Java example

// Ausgabe der Typen aller Kindknoten des aktuellen Elements
for (Node nd = ndDump.getFirstChild(  ); nd != null;
     nd = nd.getNextSibling(  )) {
    if (nd.getNodeValue(  ) != null) {
        System.out.println(nd.getNodeValue(  ));
    }
}

 

nodeName: DOMString

Contains the name of the underlying DOM object. Depending on node type, the name may map to another object attribute or a string constant. The following table shows the mappings:

Objekttyp

nodeName

Element

Tag-Name

Attr

Attributname

Text

"#text"

CDATASection

"#cdata-section"

EntityReference

Name des referenzierten Entitys

Entity

Entity-Name

ProcessingInstruction

Target

Comment

"#comment"

Document

"#document"

DocumentType

Dokumenttyp-Name

DocumentFragment

"#document-fragment"

Notation

Notationsname

Java binding
public String getNodeName( );

// Gibt den Namen des Dokumentelements aus. Node ndDoc = (Node)doc.getDocumentElement( ); System.out.println("Document root element type: " + ndDoc.getNodeName( ));

 

nodeType: unsigned short

Contains a value identifying the node’s concrete type. The following table lists the possible values, their names and the corresponding node types:

Name der Konstanten

Objekttyp

Wert der Konstanten

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

Think of parent-child and sibling relationships between document nodes as two doubly linked lists: one links parents to children, the other elements at the same level.

Java binding
public short getNodeType( );

Java example

 

// Ist der Knoten ein Knoten vom Typ Element?
public boolean isElement(Node nd) {
    return nd.getNodeType(  ) == Node.ELEMENT_NODE;
}

 

nodeValue: DOMString

This attribute tries to determine a meaningful value for the underlying DOM object. Depending on nodeType, it may be read-only or always null. The following table lists values for the different object types:

Objekttyp

nodeValue

Element

null

Attr

Attributwert

Text

textueller Inhalt des Textknotens

CDATASection

textueller Inhalt des CDATA-Blocks

EntityReference

null

Entity

null

ProcessingInstruction

kompletter Inhalt, einschließlich Target

Comment

Inhalt des Kommentars

Document

null

DocumentType

null

DocumentFragment

null

Notation

null

Exceptions

  • NO_MODIFICATION_ALLOWED_ERR

    The attribute nodeValue is read-only for the current node type. Attempting to change it therefore raises this exception.

  • DOMSTRING_SIZE_ERR

    Raised when the attribute value being read is too large for a DOMString in this implementation.

Java equivalents
public String getNodeValue( ) throws DOMException; public void setNodeValue(String nodeValue) throws DOMException;

Java example

// Für Textknoten: Umwandlung des Textknotens in Kleinbuchstaben
if (nd.getNodeType(  ) == Node.TEXT_NODE) {
    // Umwandlung in Kleinbuchstaben
    nd.setNodeValue(nd.getNodeValue().toLowerCase(  ));
}

 

ownerDocument: Document

Contains a reference to the instance of interface Document that created this Node object. Since nodes can be created only through this interface, the property ownerDocument is always set, even for new or empty nodes. Only Document nodes themselves and DocumentType nodes not yet belonging to a document may have the value null. Nodes cannot move directly to another document; import them first. This property can help determine a node’s origin.

Java binding
public Document getOwnerDocument( );

Java example

// Füge meine zwei Cents hinzu.
Document doc = elem.getOwnerDocument(  );
Text txtAdd = doc.createTextNode("Meine 0,02 EUR");
elem.appendChild(txtAdd);

 

parentNode: Node

Contains a reference to the parent node. Except for Document, DocumentFragment and Attr, all object types may have a parent. Every node within the Document hierarchy has a parent. Nodes can also exist outside the DOM tree, for example when newly created but not yet inserted, or removed from their parent’s child list using replaceChild( ) or removeChild( ). In that case, the attribute parentNode contains null.

Java binding
Node getParentNode( );

Java example

// Ein Element wird aus dem DOM-Baum entfernt.
elem.getParentNode(  ).removeChild(elem);

 

prefix: DOMString (2)

The prefix of the node’s namespace; meaningful only for node types supporting namespaces. For types ELEMENT_NODE and ATTRIBUTE_NODE, changing the prefix also changes attributes nodeName, tagName and name because a prefix change also changes the fully qualified name.

Exceptions

  • INVALID_CHARACTER_ERR

    Raised if the prefix contains illegal characters.

  • NO_MODIFICATION_ALLOWED_ERR

    Indicates that the attribute prefix is read-only in this DOM object tree.

  • NAMESPACE_ERR

    Raised if the prefix violates the rules for constructing namespace identifiers. Also raised if the attribute namespaceURI has the value null, or if XML identifier construction rules are violated, for example through illegal use of the reserved prefixes xml or xmlns. For details about namespaces, see Namespaces.

Java bindings
public String getPrefix( ); public void setPrefix(String prefix) throws DOMException;

 

previousSibling: Node

Contains a pointer to the previous sibling. If the current node is first, the value returned is null.

Java binding
public Node getPreviousSibling( );

Java example

// Ausgabe aller Knotentypen in umgekehrter Reihenfolge
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 way to retrieve or set the text content of document-tree nodes. When retrieving text, it returns the content of all Text nodes descending from the context node, without normalizing whitespace. Markup nodes (Attr, Element and so on) are ignored. When setting text, it removes all child nodes and creates a single Text node as the target’s sole child. The following table shows how the attribute textContent is constructed for different node types:

Knotentyp

Wert

ELEMENT_NODE ATTRIBUTE_NODE ENTITY_NODE ENTITY_REFERENCE_NODE DOCUMENT_FRAGMENT_NODE

Kombiniert den textContent aller Kindknoten außer Knoten der Typen COMMENT_NODE und PROCESSING_INSTRUCTION_NODE oder liefert einen leeren String, wenn keine Kindknoten vorhanden sind.

TEXT_NODE CDATA_SECTION_NODE COMMENT_NODE PROCESSING_INSTRUCTION_NODE

Liefert den gleichen Wert wie das Attribut nodeValue.

DOCUMENT_NODE DOCUMENT_TYPE_NODE NOTATION_NODE

Liefert null.

Exceptions

  • NO_MODIFICATION_ALLOWED_ERR

    Raised if the node is read-only.

  • DOMSTRING_SIZE_ERR

    Raised if the text content exceeds the maximum size of a DOMString on the implementation platform.

Java binding
public String getTextContent( ); public void setTextContent(String textContent) throws DOMException

 

Methods

The following methods are defined in the interface Node:

 

appendChild: newChild

The node newChild is appended to the end of the child list. If newChild is already elsewhere in the DOM tree, it is first removed. The method returns the node newChild.

Argument

  • newChild: Node

    The node to append. If its type is DocumentFragment, all children of newChild are inserted in order at the end of the node’s child list.

Exceptions

  • HIERARCHY_REQUEST_ERR

    Raised if the operation creates an invalid document structure, for example if the current node cannot have children or children of this type. Also raised if the current node itself descends directly or indirectly from its new child.

  • WRONG_DOCUMENT_ERR

    The node newChild belongs to a different document from the new parent.

  • NO_MODIFICATION_ALLOWED_ERR

    The intended parent node is read-only.

Java binding
public Node appendChild(Node newChild) throws DOMException;

Java example

// Verschiebe den ersten Kindknoten an das Ende der Kindknotenliste.
if (elem.getFirstChild(  ) != null) {
    elem.appendChild( elem.getFirstChild(  ) );
}

 

cloneNode: deep

Creates a parentless copy of the current node. If the argument deep has the value true, child nodes are copied recursively. Otherwise the copy contains no children.

Argument

  • deep: boolean

    The value true indicates that the child list should also be copied. The value false means that only the current node is copied.

Java binding
public Node cloneNode(boolean deep);

Java example

 

// Kopiere dieses Element und alle seine Kinder.
elem.cloneNode(true);

 

compareDocumentPosition: other (3)

Compares the relative position of the node on which it is called with that of node other. The return value is a bit mask indicating the nodes’ relative positions in document order. The following table lists the mask components and their meanings:

Konstantenname

Wert

Bedeutung

DOCUMENT_POSITION_DISCONNECTED

0x01

Die zwei Knoten sind nicht verknüpft (sie haben keinen gemeinsamen Vorfahren) und können nicht verglichen werden.

DOCUMENT_POSITION_PRECEDING

0x02

Der Knoten other steht im Dokument vor dem Zielknoten.

DOCUMENT_POSITION_FOLLOWING

0x04

Der Knoten other kommt nach dem Zielknoten.

DOCUMENT_POSITION_CONTAINS

0x08

Der Knoten other enthält den Zielknoten.

DOCUMENT_POSITION_CONTAINED_BY

0x010

Der Zielknoten enthält den Knoten other.

DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC

0x020

Die relativen Positionen sind implementierungsspezifisch, wie das bei nicht-verknüpften Knoten der Fall ist.

Argument

  • other: Node

    The other node whose position is compared.

Exception

  • NOT_SUPPORTED_ERR

    Raised when the nodes come from incompatible DOM implementations and their relative positions cannot be determined.

Java binding
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 binding-independent way to retrieve an object implementing a particular version of the specified feature. Primarily used for features beyond DOM Core.

Arguments

  • feature: DOMString

    The package name of the feature to retrieve.

  • version: DOMString

    The DOM version level to retrieve for the specified feature.

Return value

Returns an object implementing the specified feature’s APIs, or null if no implementation is available.

Java binding
public Object getFeature(String feature, String version);

 

getUserData: key (3)

Retrieves user-defined data previously attached to a node using setUserData( ). If no user data matches the specified key, returns null.

Argument

  • key: DOMString

    The unique key associated with the user data to retrieve.

Java binding
public Object getUserData(String key);

 

hasAttribute ( )

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

Java binding
public boolean hasAttribute( );

 

hasChildNodes ( )

Provides a convenient way to determine whether a node has children. Returns true if it does, otherwise false.

Java binding
public boolean hasChildNodes( );

 

insertBefore: newChild, refChild

Inserts the Node object newChild into the calling parent’s child list. The parameter refChild determines where the new node enters the list. If refChild has the value null, the new node is appended to the child list. (This is equivalent to appendChild.) If the value is not null, it is inserted before the specified node. If the new newChild node is already part of the tree, all links are first removed before insertion at the new position. If the newChild node contains a reference to the DocumentFragment object, each of its children is inserted in order before the refChild node, and a reference to the newChild node is returned.

Arguments

  • newChild: Node

    The node to insert.

  • refChild: Node

    The node before which to insert the new node, or null if appending to the child list.

Exceptions

  • HIERARCHY_REQUEST_ERR

    Raised if the operation creates an invalid document structure, for example if the current node cannot have children or children of this type. Also raised if the current node itself descends directly or indirectly from its new child.

  • WRONG_DOCUMENT_ERR

    The node newChild belongs to a different document from the new parent.

  • NO_MODIFICATION_ALLOWED_ERR

    The new parent is read-only.

  • NOT_FOUND_ERR

    Raised if the node referenced by refChild is not a child of the node performing the insertion.

  • NOT_SUPPORTED_ERR

    Raised if the DOM implementation does not support inserting DocumentType or Element nodes into a Document node.

Java binding
public Node insertBefore(Node newChild, Node refChild) throws DOMException;

Java example

// Ein neuer Knoten wird an den Anfang der Kindknotenliste eingefügt.
ndParent.insertBefore(ndNew, ndParent.getFirstChild(  ));

 

isDefaultNamespace: namespaceURI (3)

Returns true if the specified namespace URI is this node’s default namespace, otherwise false.

Argument

  • namespaceURI: DOMString

    The namespace URI to compare with the default namespace URI.

Java binding
public boolean isDefaultNamespace(String namespaceURI);

 

isEqualNode: arg (3)

Compares the current node with the node referenced by parameter other. The nodes are considered equal if all the following conditions hold:

  • They have the same type.

  • The following attributes are equal: nodeName, localName, namespaceURI, prefix, nodeValue

  • The attributes-maps are equal, containing the same number of identical nodes.

  • The childNodes lists are equal: the child subtrees are identical and every child passes the equality test with its counterpart in the other tree.

  • Only for nodes of type DocumentType: the publicId, systemId, internalSubset, entities and notations are also identical.

Returns true only if every test above succeeds; otherwise false.

Argument

  • arg: Node

    The node used for comparison.

Java binding
public boolean isEqualNode(Node arg);

 

 

isSameNode: other (3)

Returns true if the current node and the node referenced by parameter other refer to the same Node object; otherwise false is returned.

Argument

  • other: Node

    The node used for comparison.

Java binding
public boolean isSameNode(Node other);

 

isSupported: feature, version (2)

Checks whether this DOM implementation supports a particular DOM feature. For details, see “hasFeature: feature, version.” in the interface “DOMImplementation” earlier in this chapter. Returns true or false depending on whether the feature is supported.

Arguments

  • feature: DOMString

    The feature name to test. See also “hasFeature: feature, version.” in the “DOMImplementation” interface.

  • version: DOMString

    The desired feature version, for example 2.0 for DOM Level 2. If no version is specified, any version of the feature is sought.

Java binding
public boolean supports(String feature, String version);

 

lookupNamespaceURI: prefix (3)

Searches for the namespace URI associated with a prefix, starting at the current node and recursively searching its ancestors until the prefix is found. On success, returns a DOMString containing the associated namespace URI; otherwise null is returned.

Argument

  • prefix: DOMString

    The namespace prefix to find.

Java binding
public String lookupNamespaceURI(String prefix);

 

lookupPrefix: namespaceURI (3)

Searches for the prefix associated with a namespace URI, starting at the current node and recursively searching its ancestors until a matching prefix is found. On success, returns a DOMString containing the prefix; otherwise null is returned. If several prefixes match, the implementation determines which is returned.

Argument

  • namespaceURI: DOMString

    The namespace URI whose prefix is sought.

Java binding
public String lookupPrefix(String namespaceURI);

 

normalize ( ) (2)

Consecutive Text nodes are recursively merged into one. Empty Text nodes are removed from the DOM tree. This is useful, for example, when an absolute reference within a document is needed or when comparing two documents.

Java binding
public void normalize( );

 

removeChild: oldChild

The node oldChild is removed from the current node’s child list. Returns a reference to the removed Node object.

Argument

  • oldChild: Node

    The node to remove.

Exceptions

  • NO_MODIFICATION_ALLOWED_ERR

    Raised if the parent node is read-only.

  • NOT_FOUND_ERR

    The node oldChild is not a child of the current node.

  • NOT_SUPPORTED_ERR

    May be raised if this DOM implementation’s Document node does not support removing DocumentType or Element nodes.

Java binding
public Node removeChild(Node oldChild) throws DOMException;

Java example

// Entferne ein Element und alle seine Kinder
// aus dem DOM-Baum.
elem.getParentNode(  ).removeChild(elem);

 

replaceChild: newChild, oldChild

Replaces child node oldChild with newChild. If newchild is already elsewhere in the DOM tree, it is first removed. Returns the removed node oldChild.

Arguments

  • newChild: Node

    The node to insert.

  • oldChild: Node

    The node to replace.

Exceptions

  • HIERARCHY_REQUEST_ERR

    Raised if the operation creates an invalid document structure, for example if the current node cannot have children or children of the type of node newChild. Also raised if the current node itself descends directly or indirectly from newChild.

  • WRONG_DOCUMENT_ERR

    The node newChild belongs to a different document from the new parent.

  • NO_MODIFICATION_ALLOWED_ERR

    Raised if the parent node is read-only.

  • NOT_FOUND_ERR

    Raised if the node referenced by oldChild is not a child of the node performing the replacement.

  • NOT_SUPPORTED_ERR

    May be raised if this DOM implementation’s Document node does not support replacing DocumentType or Element nodes.

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

Java example

// Ersetze einen alten Knoten durch einen neuen.
ndOld.getParentNode(  ).replaceChild(ndNew, ndOld);

 

setUserData: key, data, handler (3)

The method setUserData( ) together with getUserData( ) provides a way to attach application-specific information to DOM nodes. Unique keys let multiple user objects attach to one node. Attached information must have type DOMUserData and may contain a data-handler object implementing interface UserDataHandler.

Argument

  • key: DOMString

    The unique key associated with the data parameter in the node’s user-data list.

  • data: DOMUserData

    The user data to attach.

  • handler: UserDataHandler

    An object notified when various operations are performed on the DOM node in question.

Java binding
public Object setUserData(String key, Object data, UserDataHandler handler);

  

Back to top

 

 

 

back to top