XML DOM – Accessing Nodes

Each node in an XML document can be accessed with the DOM.

Accessing Nodes:

To access a node we can choose any of the below ways:

  • Use the getElementsByTagName() method.
  • Loop through (traversing) the nodes tree.
  • Navigate the node tree, using the node relationships.

The getElementsByTagName() Method:

To get all elements with a specified tag name, the getElementsByTagName() method is used.

Syntax:

node.getElementsByTagName("tagname");

Example:

x.getElementsByTagName("title");

Explanation:

In the above example, only the <title> elements under the x node are returned.

Example: To return all <title> elements in the XML document:

xmlDoc.getElementsByTagName("title");

Explanation:

In the above example, xmlDoc is the document itself, i.e., a document node.

DOM Node List:

A node list, i.e., an array of nodes is returned by the getElementsByTagName() method.

Example:

x = xmlDoc.getElementsByTagName("title");

We can also access the <title> elements by index number. The index number starts from 0.

Example: To access the second <title>:

y = x[1];

DOM Node List Length:

The length of a node list i.e., the number of nodes is defined by the length property. Thus, by using the length property, we can loop through a node list.

Books.xml:




  
    ABC
    Author Name
    2020
    100.00
  

  
    XQuery Book
    Author 1
    Author 2
    Author 3
    Author 4
    2004
    350.00
  


Example:





Node Types:

The root node is the documentElement property of the XML document. The name of the node is the nodeName property of a node. The type of the node is the nodeType property of a node.

Example:





Output:

Traversing Nodes:

Example:





Output:

Explanation:

In the above example, we are traversing the child nodes, i.e., the element nodes of the root node. After loading “books.xml” into xmlDoc or any other XML document we will retrieve the child nodes of the root element i.e., xmlDoc. We will then check the node type, for each child node. The respective node is an element node if the node type is “1”. If the node is an element node, we will output the name of the node.

Navigating Node Relationships:

Example:





Output:

Explanation:

In the above example, we are navigating the node tree using the node relationships. After loading “books.xml” into xmlDoc or any other XML document we will retrieve the child nodes of the first book element. We will then set the “y” variable as the first child node of the first book element, and for each child node, we will check the node type. The respective node is an element node if the node type is “1”. If the node is an element node, we will output the name of the node. The “y” variable is then set to be the next sibling node. We will thus navigate through the loop again.

Please follow and like us:
Content Protection by DMCA.com