XML DOM Navigation - XML DOM

How to navigate between nodes in a XML DOM object?

The different properties of the XML DOM enable to navigate through the nodes. The nodes that can be navigated by XML DOM are:

  • parentNode
  • childNodes
  • firstChild
  • lastChild
  • nextSibling
  • previousSibling

The node tree and its relationship with other tress is shown below:

XML DOM Navigation

DOM - Parent Node

The parent node is specified as a node object by this property.

Example

By the following example an XML document, node.xml is parsed into an XML DOM object. The DOM object is navigated to the parent node through the child node

It is observed that the child node Employee navigates to its parent node.

Execution

The file is saved as navigate_example.html and the file along with the node.xml need to be on the same path on the server. In the output, the parent node of the Employee that is Company is obtained.

First Child

A Node type in which the first child name from the NodeList is represented.

Example

By the following example, an XML document node.xml is parsed into an XML DOM object which is then navigated to the first child node of the DOM object.

  • The empty nodes are avoided by the function get_firstChild(p) , which helps to obtain the firstChild element from the node list.
  • x = get_firstChild(xmlDoc.getElementsByTagName("Employee")[0]) fetches the first child node for the tag name Employee.

Execution

The file is saved as first_node_example.htm on the server path and the first child node of Employee, i.e. FirstName appears as output.

Last Child

The node type representing the last child name from the NodeList is the property of Last Child.

Example

An XML document node.xml is parsed into an XML DOM object which enables to navigate the child node from the XML DOM object.

Execution

The file is saved as last_node_example.htm on the server path and the last child node of the Employee i.e, Email appears as a result.

Next Sibling

The next child or the next sibling of the specified child element from the NodeList is represented by this property.

Example

An XML document node.xml is parsed into an XML DOM object which will then navigate to the immediate next node from the xml document.

Execution

The file is saved as nextSibling_example.htm on the server path and the next sibling node of FirstName, i.e, LastName appears as a result.

Previous Sibling

The node type that represents the previous child, the sibling prior to the specified child element from the NodeList is represented by this property.

Example

An XML document node.xml i parsed into an XML DOM object which then navigates the previous node of the last child present in the xml document.

Execution

The file is saved as previoussibling_example.htm on the server path and the previous sibling node of Email, i.e, ContactNo appears as a result.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

XML DOM Topics