May 27, 2021 XML DOM
4. GetElements ByTagName() method
5. List of DOM nodes (Node List)
6. DoM Node List Length (Node List Length)
With DOM, you have access to each node in the XML document.
DoM accesses nodes in three ways: using the getElementsByTagName() method, looping (traversing) the node tree, and navigating the node tree using the node's relationships
The following example uses the XML
file .xml.
The
function loadXMLDoc(),
located in an external JavaScript, is used to load XML files.
Use the index number in the node list to access the node
This example uses the getElementsByTagname() method to get .xml element in the "books".
Use the length property to traverse the node
This example uses the length property to traverse all the elements .xml the "books" and "books".
View the node type of the element
This example uses the nodeType property to get the .xml type of root element in "books."
Traverse element nodes
This example uses the nodeType property to handle .xml nodes in "books and data."
Use the relationship of the node to traverse the element node
This example uses the nodeType property and the nextSibling property to handle .xml nodes in "books."
You can access nodes in three ways:
1. By using the getElementsByTagName() method.
2. Cycle (traverse) the node tree.
3. Navigate through the node tree by taking advantage of the node's relationship.
GetElementsByTagName() returns all elements that have the specified label name.
The following example returns all the elements under the x element:
Note that the above instance returns only the element under the x node. To return all the elements in the XML documentation, use:
Here, xmlDoc is the document itself (document node).
The getElements ByTagName() method returns a list of nodes. The list of nodes is an array of nodes.
The following code uses loadXMLDoc() to load "books.xml" into xmlDoc, and then stores a list of nodes in the variable x:
The element in x is accessible through the index number. To access the third slt;title, you can write:
Note: The index starts at 0.
Later in this tutorial, you'll learn more about node lists.
The length property defines the length of the list of nodes (that is, the number of nodes).
You can traverse the list of nodes by using the length property:
Example explanation:
DocumentElement property stone root node of the XML document.
The nodeName property of the node is the name of the node.
The nodeType property of the node is the type of node.
You'll learn more about node properties in the next chapter of this tutorial.
The following code traverses the child nodes of the root node, which are also element nodes:
Example explanation:
The following code uses node relationships to navigate the node tree: