Tips on creating a basic list using JavaScript from an XML file

XML file

<?xml version="1.0" encoding="UTF-8"?>
<checkers>
    <data>0</data>
    <text>Blank Checker/White square</text>
</checkers>
<checkers>
    <data>3</data>
    <text>black square blank></text>
</checkers>
<checkers>
    <data>0</data>
    <text>Blank Checker/White square</text>
</checkers>

All I aim to achieve is extracting the data and creating an array/list like this:

[0,3,0] from the XML file through HTTPrequest for use in my JavaScript code.

If you can guide me in the right direction or share some resources for learning on this topic, it would be greatly appreciated. Thank you.

function loadXMLDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      this.responseText;
    }
  };
  xhttp.open("GET", "data.xml", true);
  xhttp.send();
  console.log(xhttp)


var grid = [0,3,0]

Desired final outcome required

Answer №1

To properly parse XML, it must have a single root element. Once you have this structure in place, you can utilize the DOMParser method like so:

const someXML = `<?xml version="1.0" encoding="UTF-8"?>
    <document>
        <checkers>
            <data>0</data>
            <text>Blank Checker/White square</text>
        </checkers>
        <checkers>
            <data>3</data>
            <text>black square blank></text>
        </checkers>
        <checkers>
            <data>0</data>
            <text>Blank Checker/White square</text>
        </checkers>
    </document>`

const parser = new DOMParser()
const parsedXML = parser.parseFromString(someXML, 'text/xml')

const nodes = parsedXML.querySelectorAll('checkers')

const myArray = []
nodes.forEach(node => myArray.push(node.children[0].textContent))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I create distinct component IDs effectively with the Catberry Framework?

When working with Catberry, it is essential that all components have unique IDs. How can you ensure that each ID remains distinctive even within a complex structure of nested components? ...

Creating a consistent menu header across multiple webpages without the need to manually inserting the HTML on each individual page

Is there a way to display a consistent header across all web pages without manually duplicating the HTML code for each one? I'm looking to achieve this with JavaScript, without utilizing PHP. Would it be possible to leverage Angular JS ng-include func ...

Inquiry regarding modules in Javascript/Typescript: export/import and declarations of functions/objects

I'm fresh to the realm of TypeScript and modules. I have here a file/module that has got me puzzled, and I could really use some guidance on deciphering it: export default function MyAdapter (client: Pool): AdapterType { return { async foo ( ...

Update all occurrences of a particular value to null within the Realtime Database using Firebase Cloud Functions

I need to update the values of a specific userID linked to multiple post keys in my database by setting the userID to null. The userIDs are associated with post keys located in the path: posts/ivies/userIDs in my database. Take a look at how the database i ...

Delayed execution not completely cancelled prior to component being unmounted

Alert: Avoid calling setState (or forceUpdate) on an unmounted component. While this won't cause any issues, it could suggest a memory problem in your application. Make sure to clean up all subscriptions and async tasks in the componentWillUnmount met ...

React/Next Component Changes State and Clears it in useEffect

Currently, I am faced with an issue while attempting to fetch data from an API. The problem arises during the rendering process since the useEffect function is being called multiple times. Surprisingly, everything works perfectly fine during the initial pa ...

Angular: Array in the template re-renders even if its length remains unchanged

Below is the template of a parent component: <ng-container *ngFor="let set of timeSet; index as i"> <time-shift-input *ngIf="enabled" [ngClass]="{ 'mini-times' : miniTimes, 'field field-last&ap ...

Using React and Material-UI: Implementing button functionality to call another class using hooks in the main App component

Just starting out with React/MUI and currently working on different components for a website, so the UI is not a priority at the moment. Encountering an issue when trying to create a button that links to the Sign Up page (similarly for Sign In): Error: ...

Is it possible for a beginner like me in Node.js to incorporate external npm packages into Express.js and React.js?

Recently, I embarked on a journey to learn Node.js for backend development. In the past month or so, I have familiarized myself with various concepts such as npm, Express.js, Mongoose, and MongoDB for database management. During my npm exploration, I dis ...

What is the maximum string length allowed for the parameter accepted by JavaScript's JSON.Parse() function?

Is there a maximum string length limit for the parameter accepted by JavaScript's JSON.Parse()? If I were to pass a string that surpasses this expected length, will it result in an exception being thrown or prevent the function from returning a valid ...

Utilizing AngularJS and ADAL.JS to Define Resource ID (Audience)

Is there a way to utilize adal.js within AngularJS to obtain a bearer token for the audience https://management.azure.com through JavaScript? I have created a client application in Azure AD and configured its permissions to allow access to the "Windows Az ...

Tips for passing multiple file values in an XMLHTTP POST request

Currently, I am utilizing FileReader() in order to access file values. Is there a method to initiate an Http post request for posting multiple file values as input? var fi = document.getElementById('myFile'); if (fi.files.length > 0) { ...

JavaScript is utilized to implement the k-means clustering algorithm, which demonstrates convergence yet lacks stability in its

Although I understand the concept of convergence, I am puzzled by the fact that the results vary each time the algorithm is refreshed, even when using the same dataset. Can someone point out where my methodology might be incorrect? I've been strugglin ...

Issue with external variable not being updated properly in success callback

Working through an array of data, I make updates to a variable called commentBody during each iteration. However, even though the variable is modified within the loop itself, whenever I try to access it from inside a success callback, it consistently show ...

ways to update ng-model once it has been validated

When using ng-model for input, I want to maintain the original value if an invalid number is entered. How can I accomplish this? For reference, visit the Plunker at: http://plnkr.co/edit/wX7n0jBn1Ek1py4DJHqT?p=preview The input box utilizes ng-model for b ...

Create a new CSS rule within a class, and remember to save the changes to

Upon opening page 1.html, I utilize JavaScript to dynamically add a background image to the body of the page. To achieve this, I use the following code: document.body.style.backgroundImage = "url(http://www.example.com/image.jpg)"; This code effectively ...

Exploring the Potential of Mobile Development using AngularJS

I am in the process of creating an app with the following key design objectives: Efficiency and modularity - a light core that can be expanded to create a feature-rich app in a cohesive manner Mobile focus - this app is primarily aimed at mobile platform ...

Caught up: TypeScript not catching errors inside Promises

Currently, I am in the process of developing a SPFx WebPart using TypeScript. Within my code, there is a function dedicated to retrieving a team based on its name (the get() method also returns a promise): public getTeamChannelByName(teamId: string, cha ...

Having trouble with the side menu navigation in Bootstrap?

I have a total of 5 pages on my website. Out of these, 2 main pages contain submenus/pages as well. To make users aware of the presence of submenus, I am using plus and minus icons. However, there is an issue where clicking on one submenu toggle icon doe ...

The hyperlink tag within the overlay div is unresponsive

I'm facing an issue with my overlay div (rb-overlay) that pops up when users click on a page option. The overlay takes up the entire page and includes a close button in the top right corner. However, I've noticed that the link at the end of the t ...