Getting values from an XML DOM involves accessing and extracting data stored within specific elements of an XML document. Here’s a simple explanation with an example:
Consider the following XML document (data.xml
):
Example
<library> <book> <title>Harry Potter</title> <author>J.K. Rowling</author> </book> <book> <title>The Hobbit</title> <author>J.R.R. Tolkien</author> </book> </library>
If you're working with JavaScript in a web environment, you can use the browser's DOM API to manipulate XML documents. Here’s how you can get values (text content) from elements in the XML:
Example
// Load the XML document var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var xmlDoc = this.responseXML; // Get values from elements var books = xmlDoc.getElementsByTagName("book"); 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("Book " + (i + 1) + ":"); console.log("Title: " + title); console.log("Author: " + author); console.log("-----------------------"); } } }; xhttp.open("GET", "data.xml", true); xhttp.send();
Load the XML Document: Use XMLHttpRequest to load the XML file (data.xml
in this case).
Access Elements: Use getElementsByTagName()
to get all <book>
elements. Then, for each <book>
element:
getElementsByTagName("title")
to get the <title>
element and access its textContent
property to retrieve the title value.getElementsByTagName("author")
to get the <author>
element and access its textContent
property to retrieve the author value.Output: Log the retrieved values (title
and author
) to the console. You can perform further operations with these values as needed.
textContent
is used to access the text content of an XML element in the DOM.<book>
elements, iterate through them using a loop (for
loop in this case).By following these steps, you can effectively retrieve values from elements in an XML DOM structure using JavaScript. Adjust the specific elements and structure according to your XML document and requirements.