All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Parse XML In JavaScript

Last Updated : Mar 11, 2024

Parse XML In JavaScript

In this article we will show you the solution of parse xml in JavaScript, we may additionally extract facts from XML documents & control it inside our apps by using parsing XML (eXtensible Markup Language) with JavaScript.

The ability to rapidly parse XML is important for interacting with quite a few APIs and online offerings because it's miles a broadly used format for storing and transmitting data.

We have some alternatives for parsing XML in JavaScript. One normal technique is to retrieve the XML statistics from a server the usage of the integrated XMLHttpRequest item.

Once we have the XML text, we will parse it into a document item model (DOM) structure using the DOMParser API.

As a tree of nodes represented through this DOM shape, the XML documents can be traversed and its contents extracted. Now move to the concept of parse xml in javascript.

Step By Step Guide On Parse XML In JavaScript :-

<!DOCTYPE html>
<html>
<head>
  <title>XML Parsing Example</title>
</head>
<body>
  <h1>Books</h1>
  <ul id="bookList"></ul>
  <script>
    // XML content to be parsed
    const xmlContent = `
    <books>
      <book>
        <title>JavaScript: The Good Parts</title>
        <author>Douglas Crockford</author>
      </book>
      <book>
        <title>Eloquent JavaScript</title>
        <author>Marijn Haverbeke</author>
      </book>
    </books>`;
    // Create a new DOMParser instance
    const parser = new DOMParser();
    // Parse the XML content into a DOM document
    const xmlDoc = parser.parseFromString(xmlContent, "text/xml");
    // Extract book information from the XML document
    const books = xmlDoc.getElementsByTagName("book");
    const bookList = document.getElementById("bookList");
    for (let i = 0; i < books.length; i++) {
      const title = books[i].getElementsByTagName("title")[0].textContent;
      const author = books[i].getElementsByTagName("author")[0].textContent;
      const listItem = document.createElement("li");
      listItem.textContent = `Book ${i + 1}: ${title} by ${author}`;
      bookList.appendChild(listItem);
    }
  </script>
</body>
</html>
  1. First, we have an HTML structure with an <h1> element displaying the headline "Books" and a blank <ul> element with the id "bookList" that will display the parsed book information.
  2. After that, we begin writing the JavaScript code by putting the XML content into the xmlContent variable.
  3. It stands for the XML data that has to be parsed.
  4. It provides details about two books, including their titles and authors.
  5. Next, we use the DOMParser constructor to build a clean instance of the DOMParser.
  6. With the resource of this item, we may additionally convert HTML or XML strings into DOM files.
  7. The DOMParser instance's parseFromString() technique is used to convert the XML facts right into a DOM report.
  8. The XML content material and the content type, which is "text/XML" in this situation, are the two arguments which might be required.
  9. We take records about the books from the XML record after parsing them.
  10. Get all of the factors with the tag name "ebook" with the aid of calling getElementsByTagName() on the xmlDoc item.
  11. This produces a listing of e-book components.
  12. Using getElementById(), we also can get the <ul> element with the identity "bookList".
  13. For later use, this detail is kept inside the bookList variable.
  14. Now, we use a for loop.
  15. Using getElementsByTagName() on each book element, we retrieve the name and creator of every e-book inside the loop.
  16. Since there may be only one identify and one creator for each ebook, we get right of entry to the primary element inside the lower back series and acquire their textual content content material the use of textContent.
  17. To show the e-book statistics, we create an <li> detail the use of document.CreateElement().
  18. Using template literals, we set the textContent of the <li> detail to a string that contains the name and writer of the ebook.
  19. Finally, we use appendChild() to append each <li> detail to the bookList detail.
  20. Each book is now added as a new <li> item in the <ul> detail.

Conclusion :-

As a result, we have been capable of understand how to study XML in Javascript.

We also determined that parsing XML with JavaScript permits us to successfully extract statistics from XML documents.

I hope this article on parse xml in JavaScript helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Amruta

Amruta is an Experienced web developer with 4 years for experience she completed her master's with MCA and passionate about programming Languages for creating technical contents like HTML, CSS, JavaScript, Java, Python, PHP, jQuery.

Follow Amruta On Linkedin 🡪