The Wayback Machine - https://web.archive.org/web/20241119000221/https://www.geeksforgeeks.org/how-to-parse-xml-in-javascript/
Open In App

How to Parse XML in JavaScript?

Last Updated : 19 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Parsing XML data is important because it allows JavaScript applications to extract structured information from XML documents. We will explore two different approaches to Parse XML in JavaScript.

Below are the approaches to parsing XML in JavaScript:

Using DOM Parser

In this approach, we are using the DOM Parser, which is built into browsers, to parse XML data. The parser converts the XML into a DOM object, allowing easy traversal and extraction of elements using standard DOM methods.

Run the below command to install xmldom library:

npm install xmldom

Example: The below example uses DOM Parser to Parse XML in JavaScript.

JavaScript
const {
  DOMParser
} = require('xmldom');
const xmlData = `
  <organization>
    <name>GeeksforGeeks</name>
    <founder>Sandeep Jain</founder>
    <location>Noida</location>
  </organization>
`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlData,
                                    'text/xml');
const orgName = xmlDoc.getElementsByTagName('name')
                   [0].textContent;
const founder = xmlDoc.getElementsByTagName('founder')
                   [0].textContent;
const location = xmlDoc.getElementsByTagName('location')
                    [0].textContent;
console.log('Organization Name:', orgName);
console.log('Founder:', founder);
console.log('Location:', location);

Output:

Organization Name: GeeksforGeeks
Founder: Sandeep Jain
Location: Noida

Using xml2js Library

In this approach, we are using the xml2js library in JavaScript to parse XML data asynchronously. The parseString function converts XML into a JavaScript object, enabling easy access to elements for further processing or display.

Run the below command to install xml2js library:

npm install xml2js 

Example: The below example uses xml2js Library to Parse XML in JavaScript.

JavaScript
const {
  parseString
} = require('xml2js');
const xmlData = `
  <organization>
    <name>GeeksforGeeks</name>
    <founder>Sandeep Jain</founder>
    <location>Noida</location>
  </organization>
`;
parseString(xmlData, (err, result) => {
  if (err) {
    console.error('Error parsing XML:', err);
    return;
  }
  const orgName = result.organization.name[0];
  const founder = result.organization.founder[0];
  const location = result.organization.location[0];
  console.log('Organization Name:', orgName);
  console.log('Founder:', founder);
  console.log('Location:', location);
});

Output:

Organization Name: GeeksforGeeks
Founder: Sandeep Jain
Location: Noida

Previous Article
Next Article

Similar Reads

How to parse and process HTML/XML using PHP ?
In this article, we will learn how to process XML using PHP. We have already learnt the basics of XML and their differences with respect to HTML. Different elements of XML can be learnt from XML Elements to understand the working of the following programs. The simplexml_load_string() function is used to parse the given XML and then the XML object c
2 min read
Difference Between text/xml and application/xml for Webservice Response
application/xmlThis is the recommended media type for XML data according to the IETF specifications [RFC 7303]. It signifies that the XML content might not be human-readable and could potentially contain processing instructions or other non-human-consumable elements. Syntax:Content-Type: application/xmlThis example demonstrates a web service respon
2 min read
JavaScript JSON parse() Method
The JSON.parse() method in JavaScript is used to parse a JSON string which is written in a JSON format and returns a JavaScript object. Syntax: JSON.parse( string, function ) Parameters: This method accepts two parameters as mentioned above and described below: string: It is a required parameter and it contains a string that is written in JSON form
2 min read
How to parse URL using JavaScript ?
Given an URL and the task is to parse that URL and retrieve all the related data using JavaScript. Example: URL: https://www.geeksforgeeks.org/courses When we parse the above URL then we can find hostname: geeksforgeeks.com path: /courses Method 1: In this method, we will use createElement() method to create a HTML element, anchor tag and then use
2 min read
JavaScript SyntaxError - JSON.parse: bad parsing
This JavaScript exception thrown by JSON.parse() occurs if string passed as a parameter to the method is invalid. Message: SyntaxError: JSON.parse: unterminated string literal SyntaxError: JSON.parse: bad control character in string literal SyntaxError: JSON.parse: bad character in string literal SyntaxError: JSON.parse: bad Unicode escape SyntaxEr
2 min read
How to parse a URL into hostname and path in javascript ?
We can parse a URL(Uniform Resource Locator) to access its component and this can be achieved using predefined properties in JavaScript. For Example, the first example parses the URL of the current web page and the second example parses a predefined URL. Example 1:This example parses the URL of the current web page. C/C++ Code <body style="
1 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
How does the JSON.parse() method works in JavaScript ?
The JSON.parse() method in JavaScript is used to parse a JSON (JavaScript Object Notation) string and convert it into a JavaScript object. JSON is a lightweight data-interchange format that is easy for humans to read and write, and it is also easy for machines to parse and generate. Example: Here, JSON.parse() take a JSON-formatted string (jsonStri
1 min read
How to parse HTTP Cookie header and return an object of all cookie name-value pairs in JavaScript ?
To parse HTTP Cookie header we will spilt the cookies data and create objects from the key-value extracted from cookies. Cookies are simply small text files that a web server sends to the user's browser. They contain the following data. Name-value pair with actual data.The expiry date for when the cookie becomes invalid.Domain and path of the serve
3 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
How to Catch JSON Parse Error in JavaScript ?
JSON (JavaScript Object Notation) is a popular data interchange format used extensively in web development for transmitting data between a server and a client. When working with JSON data in JavaScript, it's common to parse JSON strings into JavaScript objects using the JSON.parse() method. However, parsing JSON data can sometimes lead to errors, e
1 min read
How to Parse JSON in JavaScript ?
Parse JSON in JavaScript, accepting a JSON string as input and returning a corresponding JavaScript object with two methods, using JSON.parse() for parsing JSON strings directly and employing the fetch API to parse JSON responses from web APIs. These techniques are crucial for seamless data manipulation and retrieval in your JavaScript projects. Be
2 min read
How to Parse JSON Data in JavaScript ?
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write. It is easy for machines to parse and generate it. In JavaScript, parsing JSON data is a common task when dealing with APIs or exchanging data between the client and server. Table of Content Using JSON.parse() MethodUsing eval() Func
4 min read
JavaScript Date parse() Method
The JavaScript Date parse() method parses a date string and returns the number of milliseconds between the date string and midnight of January 1, 1970, UTC. If the argument is an invalid date string, it returns NaN (Not a Number). Syntax:Date.parse(datestring);Parameters:This method accepts a single parameter: datestring: This parameter holds the d
3 min read
How to Parse S-expressions in JavaScript?
The most simple and powerful notation used in Lisp programming is S-expressions and they are composed of atoms, say numbers or symbols or strings and lists (which too are S-expressions) parsing S-expressions in JavaScript can be done using a few basic techniques. What are S-expressions?To represent nested list data structures, we use s-expressions,
4 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 using JavaScript, using different methods. Table of Co
4 min read
How to Parse Float with Two Decimal Places in JavaScript?
JavaScript provides an inbuilt parseFloat() method to parse a string and returns a floating-point number. Below are the approaches to parse float to two decimal places in JavaScript: Table of Content Using parseFloat() MethodUsing Custom parseFloat Method Approach 1: Using parseFloat() MethodThe parseFloat() method converts a string to a floating-p
2 min read
How to Loop through XML in JavaScript ?
In JavaScript, looping over XML data is important for processing and extracting information from structured XML documents. Below is a list of methods utilized to loop through XML. Table of Content Using for loop with DOMParser and getElementsByTagNameUsing Array.from with DOMParser and childNodesUsing for loop with DOMParser and getElementsByTagNam
2 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 ParserIn this approach, we are using the DOMParser fr
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 Using DOMParser and XMLSerializerUsing xmlbuilder2
2 min read
How to Fetch XML with Fetch API in JavaScript ?
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
3 min read
How to Load XML from JavaScript ?
Loading XML data into JavaScript is a common task, whether it's for parsing user input or fetching data from a server. The below-listed approaches can be used to load XML from JavaScript. Table of Content Parsing XML String DirectlyFetching XML Data from an External SourceParsing XML in Node.js using xml2jsParsing XML String DirectlyThis approach i
4 min read
How to create XML Dynamically using 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 create XML Dynamically using JavaScript: Table of Content Using DOM ManipulationUsing Template LiteralsUsing DO
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 specified schema. XML (Extensible Markup Language): It
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: Table of Content Using DOM ParserUsing XMLHttpRequest
2 min read
Convert XML to JSON using JavaScript
Convert XML to JSON effortlessly using JavaScript, enabling seamless integration and manipulation of XML data within your applications. JavaScript libraries like xml-js and xmldom Library simplify the conversion process, ensuring compatibility and efficiency. Below are the approaches to convert XML to JSON in JavaScript: Table of Content Using xml-
2 min read
How to get Attribute Value from XML using JavaScript?
To get the attribute values from XML in JavaScript, We can use DOM manipulation or XPath querying and even use regular expressions to efficiently retrieve attribute values from XML documents. Below are the approaches to get attribute value from XML with Java Script: Table of Content Using DOM ParserUsing XPathUsing Regular ExpressionsUsing the attr
3 min read
Read XML file and print the details as tabular data by using JavaScript
Reading an XML file and printing its details as tabular data using JavaScript involves parsing the XML content, extracting relevant data, and then displaying it in a structured table format. This can be done by manipulating the Document Object Model (DOM) and creating HTML tables dynamically in the browser. PrerequisitesBasic Knowledge HTMLBasic Kn
3 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 the XML to JSON object. Table of Content Convert X
2 min read
Python | Parse a website with regex and urllib
Let's discuss the concept of parsing using python. In python we have lot of modules but for parsing we only need urllib and re i.e regular expression. By using both of these libraries we can fetch the data on web pages. Note that parsing of websites means that fetch the whole source code and that we want to search using a given url link, it will gi
2 min read
Article Tags :
three90RightbarBannerImg