There are usually several ways to read XML files in JavaScript, depending on your running environment (such as the browser side or environment). Here are some common solutions:
1. Read XML files in the browser environment (using XMLHttpRequest or Fetch API)
Using XMLHttpRequest
const xhr = new XMLHttpRequest(); ('GET', 'path/to/your/', true); = function () { if ( === 4 && === 200) { const xmlDoc = ; (xmlDoc); // Here you can manipulate XML DOM } }; ();
useFetch API
(More modern way)
fetch('path/to/your/') .then(response => ()) .then(data => { const parser = new DOMParser(); const xmlDoc = (data, 'application/xml'); (xmlDoc); // Operate xmlDoc }) .catch(error => ('Error loading the XML file:', error));
2. Read XML files in the environment
In reading XML files, it is often necessary to use external libraries, e.g.fs
Modules andxml2js
Wait for the library to parse XML.
Use the fs and xml2js library
Install first
xml2js
Library (if not installed):
npm install xml2js
const fs = require('fs'); const xml2js = require('xml2js'); // Read XML files('path/to/your/', 'utf8', (err, data) => { if (err) { ('Error reading XML file:', err); return; } // parse XML strings as JavaScript objects const parser = new (); (data, (err, result) => { if (err) { ('Error parsing XML:', err); return; } (result); // parsed JavaScript object }); });
3. Manipulate XML content
Whether in the browser environment or environment, once you have successfully read and parsed the XML file, you can manipulate the data by accessing the parsed XML DOM or JavaScript object. For example:
In the browser environment, standard DOM methods can be used to query and modify XML elements.
const title = ('title')[0].textContent; (title);
In the environment, then elements can be accessed through the converted JavaScript object.
([0]); // AssumptionsXMLSimilar structure <root><title>...</title></root>
summary
- In the browser environment, you can use
XMLHttpRequest
orFetch API
to load the XML file and useDOMParser
parse XML. - In the environment, you can use
fs
Module reads files and combines themxml2js
library to parse XML files.
This is the end of this article about several methods of reading XML files in JavaScript. For more related JavaScript, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!