Retrieving a specific XML field value using JavaScript

I am working with an XML string that contains data about the capitals of different countries. How can I extract the capital values for Washington, DC and Paris from this XML?

<Country>
    <USA>
    <Capital>"Washington, D.C"</Capital>
    </USA>
    <France>
    <Capital>"Paris"</Capital>
    </France>
</Country>

Answer №1

One way to parse XML in JavaScript is by using the DOMParser:

var xml = `<Country>
    <USA>
    <Capital>"Washington, D.C"</Capital>
    </USA>
    <France>
    <Capital>"Paris"</Capital>
    </France>
</Country>`

var parser = new DOMParser();
var doc = parser.parseFromString(xml, "application/xml");
doc.querySelectorAll('Capital').forEach(
  (cap) => console.log(cap.textContent));

Answer №2

Implementing the solution using jQuery. Utilizing jQuery, this task can be effortlessly achieved by:

var data = `<Country>
    <USA>
    <Capital>"Washington, D.C"</Capital>
    </USA>
    <France>
    <Capital>"Paris"</Capital>
    </France>
</Country>`;

$(data).find("Capital").each(function(){
    console.log($(this).text());
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

Utilizing ng-href in Angular.js Template: A Guide

I am attempting to develop a simple Single Page Application (SPA) with just one index.html file that includes templates. However, I encountered an issue with the ng-href directive: <a ng-href="#/myPage">myPage</a> This works fine in index.h ...

Retrieve webpage content using an ajax request in JavaScript

I'm working on an HTML page with an Ajax call to load table content. <html> .... <script sec:haspermission="VIEW_NOTE" th:inline='javascript'> require(['app/agent/viewGlobalAgent'], function (){ ...

Utilize Google API V3 to create a dropdown selection list of locations, extracting latitude and longitude values from a JSON text file

I am working on creating a map using Google Maps API v3. I have implemented a dropdown select list for different places and I am pulling the latitude and longitude values from it. Initially, I manually added the options like this: <option value= ...

How to achieve a reverse slideToggle effect with jQuery when refreshing the page

After creating a custom menu on Wordpress using jQuery slideToggle to toggle dropdown on hover, everything seemed to be working perfectly. However, I noticed that when I refreshed the page while moving my cursor between two menu items with dropdown menus, ...

I am looking to extract solely the numerical values

Programming Tools ・ react ・ typescript ・ yarn I am trying to extract only numbers using the match method But I keep encountering an error Error Message: TypeError: Cannot read property 'match' of undefined const age="19 years ...

Is it possible to generate various resolutions of an image simultaneously?

While trying to download wallpapers from a link on this website, I encountered an issue. Upon clicking the download button, a new page opened with the URL "https://images.wallpapersden.com/image/download/street-fighter-fortnite_bGtoaW6UmZqaraWkpJRmbmdlrW ...

What is the best way to attach an event listener to a child window in vuejs?

After creating a component in vue 3, I found myself in need of a new window, similar to a popup, using the window.open(url, name, config) method. Furthermore, I required a way to execute a function when this child window is closed. (Please bear in mind th ...

ReactJS - Divs enclosed within a sub component do not reflect state changes

Looking for help with my React class. I'm trying to change the class of the outermost div when menuClicked() is called, but it's not working as expected. Can someone provide insight into how state scope works in this situation? import React, {Co ...

Only display entries with no content

When attempting to filter data from a search, all results are being displayed on the submit button even when entering 1, 2, or 3. Here is my code below. Please let me know if I am making a mistake somewhere. ...

JQuery Chosen extension - Go back to "Choose an option"

This is a select element with the Chosen plugin applied to it: <label class="radio-inline"><input type="radio" name="reset" value="reset">Reset</label> <select id="listclient"> <option value=""></option> <option val ...

unable to fix slideshow glitch after multiple cycles

I've encountered an issue with my custom JavaScript picture scroll. After 3-4 photo changes, the script crashes the page unexpectedly. I'm not sure what is causing this problem! Can someone provide assistance? Below is the code snippet: <di ...

Disable the functionality of the next and previous buttons for the Bootstrap carousel when clicking on the outer

Here is the code for the carousel: The next/prev button functions under its respective div, how can I stop it? When I click on the div below the carousel, the carousel continues to move as usual. Below the carousel div, there is another one with a tabbi ...

adding a fresh feature to the existing array of functions linked to a JavaScript event

If I have an input button like this: <input type="submit" value="Submit" onclick="fxn1();fxn2();fxn3();"/> Now, I want to add a new function named fxn() to the list of functions already assigned to the onclick event. How can I achieve this consider ...

React rejects the rendering of a div element

I've encountered an issue with my web application where the /tasks section is not displaying any content, even though everything else is working fine. I've double-checked my code and it seems to be identical to the other elements. import React, ...

The y-axis max property in Highcharts does not effectively hide plot bands and labels

I have set up two separate jsfiddles to demonstrate my issue. The first jsfiddle represents the desired behavior, while the second one displays the problem I am encountering. In the first jsfiddle (https://jsfiddle.net/n5ua6krj/1/), the y-axis[0] does not ...

Setting a base path in React: A step-by-step guide

I'm facing a challenge with my React app where I need it to function on subdirectories within a URL structure, such as this example: www.mysite.com/reactapp I've attempted redirection, setting a base URL on the router, and including the path in ...

Steps to bring an image forward on a canvas to enable its onclick function

One of the challenges I'm facing involves an image of a pawn on a board. The image is set up with an onclick function that should trigger an alert when clicked. However, there is a canvas positioned above the image, which is interfering with the funct ...

Challenges with JavaScript objects while using d3.js

I have been working on rendering a map using d3 within an HTML page that is running on a django web framework. One of the examples I came across from d3's sample archives can be found at this link: http://bl.ocks.org/NPashaP/a74faf20b492ad377312 Upon ...

Having trouble transferring sound files to Cloudinary API through javascript

I have successfully implemented a function in my React Native application to upload images to Cloudinary. Now, I am trying to modify the function to upload audio files as well. Despite specifying the "resource_type" parameter as "raw", "video", or "auto", ...

The AJAX query for validating IDs in a JSP page consistently produces identical outcomes

I have been implementing a feature to check IDs using AJAX in JSP. When a user tries to create a new account, they enter the desired ID and AJAX checks if the ID already exists in the database. If the ID is found, it returns 'n' which is then dis ...