May 27, 2021 XML DOM
The list of nodes is returned by the getElementsByTagName() method and the childNodes property.
The following example uses the XML
file .xml.
The
function loadXMLDoc(),
located in an external JavaScript, is used to load XML files.
Get the text from the first element
This example uses the getElementsByTagName() method to get the text from the first element in .xml books".
Use the length property to traverse the node
This example uses the node list and the length property to traverse all the elements of the "books.xml" in the "books".
Gets the properties of the element
This example uses a list of properties .xml get properties from the first element in "books."
When you use properties or methods such as childNodes or getElementsByTagName(), the node list object is returned.
The node list object represents the list of nodes in the same order as in XML.
The nodes in the node list are accessed using an index number that starts at 0.
The following image represents .xml of nodes in the "books" element:
The following snippet loads "books.xml" into xmlDoc by using loadXMLDoc() and returns a list of nodes of the title element in "books.xml":
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title");
After the above statement is executed, x is the node list object.
The following snippet returns text from the first element in the node list (x):
After the above statement is executed, txt is "Everyday Italian".
The node list object keeps itself up to date. If an element is deleted or added, the list updates automatically.
The length property of the node list is the number of nodes in the list.
The following snippet loads "books.xml" into xmlDoc by using loadXMLDoc() and returns the number of elements in "books.xml":
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('title').length;
After the above statement is executed, x is 4.
The length of the node list can be used to traverse all the elements in the list.
The following snippets use the length property to traverse the list of elements:
Output:
Example explanation:
The attributes property of the element node returns a list of property nodes.
This is called a named node map and is similar to a list of nodes, except for some differences in methods and properties.
The list of properties keeps itself up to date. If you delete or add properties, the list updates automatically.
The following snippet loads "books.xml" into xmlDoc by using loadXMLDoc() and returns a list of property nodes for the first element of the "books.xml" element:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book')[0].attributes;
After the above code is executed, x.length is equal to the number of properties, and the property node can be returned using x.getNamedItem().
The following snippet shows the value of a book's "category" property and the number of its properties:
Output:
Example explanation: