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.
node.getElementsByTagName("
tagname");
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];
Note: The index starts at 0.
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
}
Try it Yourself »
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>";
}
}
Try it Yourself »
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;
}
Try it Yourself »
Example explained:
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!