Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing XML

XML DOM Get Values:



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:

Example XML Document

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>

Getting Values Using JavaScript (for Web Environment)

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();

Explanation

  1. Load the XML Document: Use XMLHttpRequest to load the XML file (data.xml in this case).

  2. Access Elements: Use getElementsByTagName() to get all <book> elements. Then, for each <book> element:

    • Use getElementsByTagName("title") to get the <title> element and access its textContent property to retrieve the title value.
    • Use getElementsByTagName("author") to get the <author> element and access its textContent property to retrieve the author value.
  3. Output: Log the retrieved values (title and author) to the console. You can perform further operations with these values as needed.

Important Notes

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.




Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java