HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
With the DOM, you can access every node in an XML document
You can access a node in three ways:
getElementsByTagName() returns all elements with a specified tag name.
Syntax
node.getElementsByTagName("tagname");
Example
The following example returns all <title> elements under the x element:
x.getElementsByTagName("title");
Note that the example above only returns <title> elements under the x node. To return all <title> elements in the XML document use:
xmlDoc.getElementsByTagName("title");
where xmlDoc is the document itself (document node).
The getElementsByTagName() method returns a node list. A node list is an array of nodes.
x = xmlDoc.getElementsByTagName("title");
The <title> elements in x can be accessed by index number. To access the third <title> you can write::
y = x[2];
The length property defines the length of a node list (the number of nodes).
You can loop through a node list by using the length property:
var
x = xmlDoc.getElementsByTagName("title");
for (i = 0; i <x.length; i++) {
//
do something for each node
}
The documentElement property of the XML document is the root node.
The nodeName property of a node is the name of the node.
The nodeType property of a node is the type of the node.
You will learn more about the node properties in the next chapter of this tutorial.
The following code loops through the child nodes, that are also element nodes, of the root node:
txt = "";
x = xmlDoc.documentElement.childNodes;
for (i = 0; i <x.length; i++)
{
// Process only element nodes (type 1)
if (x[i].nodeType == 1) {
txt += x[i].nodeName + "<br>";
}
}
Example explained:
The following code navigates the node tree using the node relationships:
x = xmlDoc.getElementsByTagName("book")[0];
xlen = x.childNodes.length;
y = x.firstChild;
txt = "";
for (i = 0; i <xlen; i++)
{
// Process only element nodes (type 1)
if (y.nodeType == 1) {
txt += y.nodeName + "<br>";
}
y = y.nextSibling;
}
Example explained: