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 Accessing:



Accessing XML DOM (Document Object Model) in simple terms involves navigating through the structure of an XML document to retrieve or manipulate its elements, attributes, text, etc. You can access elements based on their tag names, attributes, or their position in the document.

Here's how you can do it with an example:

Consider the following XML document

        

Example

<bookstore> <book category="fiction"> <title>Harry Potter</title> <author>J.K. Rowling</author> </book> <book category="fantasy"> <title>The Hobbit</title> <author>J.R.R. Tolkien</author> </book> </bookstore>

Let's say you want to access the title and author of the first book.

In JavaScript using the DOM API, you can do it like this:

        

Example

// Parse the XML string into a DOM object var xmlDoc = new DOMParser().parseFromString(xmlString, "text/xml"); // Access the first book element var firstBook = xmlDoc.getElementsByTagName("book")[0]; // Access the title and author elements within the first book var title = firstBook.getElementsByTagName("title")[0].textContent; var author = firstBook.getElementsByTagName("author")[0].textContent; // Output the title and author console.log("Title: " + title); console.log("Author: " + author);

In this example:

  1. We parse the XML string into a DOM object using DOMParser.
  2. We access the first book element using getElementsByTagName("book"), which returns a NodeList containing all book elements, and then we select the first one using [0].
  3. Within the first book element, we access the title and author elements using getElementsByTagName("title") and getElementsByTagName("author"), respectively.
  4. We extract the text content of the title and author elements using textContent.
  5. Finally, we output the title and author to the console.

This is just a basic example, but you can access XML DOM nodes in various ways based on your requirements, such as using XPath queries or specific DOM methods provided by your programming language.




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