A XML Node can be accessed in three ways. They are:
- With getElementsByTagName() Method
- Looping Nodes Tree
- Navigating Node Tree
getElementsByTagName() returns all elements with a specified tag name.
Syntax:
[xml]node.getElementsByTagName("tagname");[/xml]
Example: Below is the example for getElement ByTagName() method which uses x as the node and all the <p> elements under the x.
[xml]x.getElementsByTagName("p");[/xml]
If needed to return all the elements of the <p> XML Document, then use the below code.
[xml]xmlDoc.getElementsByTagName("p");[/xml]
The below code consists of root node and child nodes. The process of looping will be undergone through child nodes. This process is also termed as Traversing.
Example:
[javascript]
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var x, i, xmlDoc, txt;
xmlDoc = xml.responseXML;
txt = "";
x = xmlDoc.documentElement.childNodes;
for (i = 0; i < x.length; i++) {
if (x[i].nodeType == 1) {
txt += x[i].nodeName + "<br>";
}
}
document.getElementById("demo").innerHTML = txt;
}
[/javascript]
In the above example, books.xml is the XML document with the root element
xmlDoc
and to check the child nodes are present or not, loop is applies. If the nodeType equals to 1 then it is considered as element node and outputted as same.
As discussed Parent nodes have Children. Children of same level are called Siblings (brothers or sisters). Every node, except the root, has exactly one parent node. A node can have any number of children and Siblings can be referred as nodes with same parent.
Example:
[javascript]
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var x, y, i, xlen, xmlDoc, txt;
xmlDoc = xml.responseXML;
x = xmlDoc.getElementsByTagName("book")[0];
xlen = x.childNodes.length;
y = x.firstChild;
txt = "";
for (i = 0; i < xlen; i++) {
if (y.nodeType == 1) {
txt += i + " " + y.nodeName + "<br>";
}
y = y.nextSibling;
}
document.getElementById("demo").innerHTML = txt;
}
[/javascript]