XML DOM (Document Object Model) Node Lists are collections of nodes that are returned by various methods and properties when working with XML documents programmatically. These Node Lists contain nodes such as elements, attributes, text nodes, etc., and they allow you to iterate over and access these nodes.
Here's a simple explanation with an example:
Suppose you have an XML document like this:
Example
<bookstore> <book> <title>Harry Potter</title> <author>J.K. Rowling</author> </book> <book> <title>The Hobbit</title> <author>J.R.R. Tolkien</author> </book> </bookstore>
And you want to access all the <book>
elements in this document.
In many programming languages like JavaScript, when you parse this XML document using XML DOM methods, you often get a Node List when you query for elements. For example, in JavaScript using the DOM API, you might do something like this:
Example
var xmlDoc = new DOMParser().parseFromString(xmlString, "text/xml"); var books = xmlDoc.getElementsByTagName("book");
Here, books
is a Node List containing all the <book>
elements in the XML document.
You can then iterate over this Node List to access individual <book>
elements and their contents. For example, you might want to extract the title and author of each book:
Example
for (var i = 0; i < books.length; i++) { var title = books[i].getElementsByTagName("title")[0].textContent; var author = books[i].getElementsByTagName("author")[0].textContent; console.log("Title: " + title + ", Author: " + author); }
In this example, books
is a Node List containing all the <book>
elements. You iterate over each book in the Node List, extract the title and author by querying for the <title>
and <author>
elements within each book, and then log the title and author to the console.
Node Lists are very useful for working with collections of nodes in XML DOM, allowing you to perform operations on multiple nodes at once.