Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Convert XML to JSON in JavaScript?
Next article icon

How to Fetch XML with Fetch API in JavaScript ?

Last Updated : 18 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The JavaScript fetch() method retrieves resources from a server and produces a Promise. We will see how to fetch XML data with JavaScript's Fetch API, parse responses into XML documents, and utilize DOM manipulation for streamlined data extraction with different methods.

These are the following methods:

Table of Content

  • Using response.text() Method
  • Using FileReader Object

Using response.text() Method

To fetch the XML data, use the fetch() function. However, as the Fetch API lacks native XML parsing support, handling the response involves alternative methods. Convert it to text and then parse it using an XML parser like DOMParser. First, use the fetch() function to request the XML file. If the response is successful, convert it to text using the response.text(). Use DOMParser to parse the XML text into an XML document. Handle any errors that may occur during the fetch operation or XML parsing.

Example: This example shows the implementation of the above-explained approach.

JavaScript
fetch('https://codetogo.io/api/users.xml')     .then(response => {         if (!response.ok) {             throw new Error('Network response was not ok');         }         return response.text();     })     .then(xmlText => {         const parser = new DOMParser();         const xmlDoc = parser.parseFromString(xmlText,                                             'text/xml');          // Now you can work with the parsed XML document         console.log(xmlDoc);     })     .catch(error => {         console.error(`There was a problem with                        the fetch operation:`, error);     }); 

Output: The browser console will show you the output.

yu

Using FileReader Object

To fetch XML data using both the Fetch API and the FileReader API in JavaScript, first use the Fetch API to retrieve the XML file. Then, utilize the response.blob() method to obtain the response body as a Blob object. Next, employ the FileReader API to read the Blob as text using FileReader.readAsText(). Finally, parse the XML text into a document object using DOMParser, enabling further processing of the XML data within the application.

Example: This example shows the implementation of the above-explained approach.

JavaScript
fetch('https://codetogo.io/api/users.xml')     .then(response => {         if (!response.ok) {             throw new Error('Network response was not ok');         }         return response.blob();     })     .then(blob => {         const reader = new FileReader();         reader.onload = function (event) {             const xmlText = event.target.result;             const parser = new DOMParser();             const xmlDoc = parser.parseFromString(xmlText,                                                   'text/xml');              // Now you can work with the xmlDoc             console.log(xmlDoc);         };         reader.readAsText(blob);     })     .catch(error => {         console.error(`There was a problem with                        the fetch operation:`, error);     }); 

Output: The browser console will show you the output.

yu

Note: The DOMParser method will give error if you run that in NodeJs environment. You must use browser console to see your output by linking it to the HTML file. Also, you must use CORS chrome extension that will allow you to use fetch function and DOMParser.


Next Article
How to Convert XML to JSON in JavaScript?

G

gfgking
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

  • How To Use JavaScript Fetch API To Get Data?
    An API is a set of rules, protocols, and tools that allows different software applications to communicate with each other. One of the popular ways to perform API requests in JavaScript is by using Fetch API. What is the Fetch API?The Fetch API is a built-in JavaScript feature that allows you to make
    4 min read
  • How to use JavaScript Fetch API to Get Data ?
    The Fetch API provides a JavaScript interface that enables users to manipulate and access parts of the HTTP pipeline such as responses and requests.  Fetch API has so many rich and exciting options like method, headers, body, referrer, mode, credentials, cache, redirect, integrity, and a few more. H
    2 min read
  • How to Create XML in JavaScript ?
    In JavaScript, XML documents can be created using various approaches. You can define elements, attributes, and content to structure the XML data, and then serialize it into a string for use or storage. There are several approaches to creating XML in JavaScript which are as follows: Table of Content
    2 min read
  • How to connect to an API in JavaScript ?
    An API or Application Programming Interface is an intermediary which carries request/response data between the endpoints of a channel. We can visualize an analogy of API to that of a waiter in a restaurant. A typical waiter in a restaurant would welcome you and ask for your order. He/She confirms th
    5 min read
  • How to Convert XML to JSON in JavaScript?
    To convert XML to JSON in JavaScript, various methods and libraries and be used. Here, we use xml-js library that provides xml2json function to convert XML to JSON data. It takes XML data as input and gives the JSON objects as output. We can also use the DOMParser from the xmldom package to convert
    2 min read
  • How to Validate XML against XSD in JavaScript ?
    XML (Extensible Markup Language) is a widely used format for storing and exchanging structured data. XSD (XML Schema Definition) is a schema language used to define the structure, content, and data types of XML documents. Validating XML against XSD ensures that the XML document conforms to the speci
    4 min read
  • How to Validate XML in JavaScript ?
    Validation of XML is important for ensuring data integrity and adherence to XML standards in JavaScript. There are various approaches available in JavaScript using which validation of the XML can be done which are described as follows: Table of Content Using DOM ParserUsing Tag MatchingUsing DOM Par
    2 min read
  • How To Fetch And Parse RSS Feeds In JavaScript?
    RSS (Really Simple Syndication) feeds are widely used for sharing updates from websites in a standardized XML format. By fetching and parsing RSS feeds, you can access the latest content from blogs, news sites, and other platforms. In this article, we’ll explore how to fetch and parse RSS feeds usin
    4 min read
  • How to Access XML Data via JavaScript ?
    XML stands for Extensible Markup Language. It is a popular format for storing and exchanging data on the web. It provides a structured way to represent data that is both human-readable and machine-readable. There are various approaches to accessing XML data using JavaScript which are as follows: Tab
    2 min read
  • Fetch API in JavaScript
    The Fetch API is a modern interface in JavaScript that allows you to make HTTP requests. It replaces the older XMLHttpRequest method and provides a cleaner and more flexible way to fetch resources asynchronously. The Fetch API uses Promises, making it easier to work with asynchronous data. Syntax fe
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences