Querying an XML document to locate a specific element/attribute value and extract that element

After writing a code that extracts elements from an XML product catalog and displays them in a table, I now aim to retrieve only one specific product with all its details based on a given SERIAL. For instance, I want to fetch the product from the catalog by matching it with a particular SERIAL.

Shown below is my XML document:

<CATALOG>
    <PRODUCT>
       <SERIAL>123ABC</SERIAL>
       <PRODNR>1234</PRODNR>
       <PRODNM>COOLER</PRODNM>
       <ACCNAME>JOHN</ACCNAME>
       <NRDOC>0001</NRDOC>
    </PRODUCT>
    <PRODUCT>
       <SERIAL>234BCD</SERIAL>
       <PRODNR>2345</PRODNR>
       <PRODNM>MOUSEPAD</PRODNM>
       <ACCNAME>STEVE</ACCNAME>
       <NRDOC>0002</NRDOC>
    </PRODUCT>
    <PRODUCT>
       <SERIAL>345CDE</SERIAL>
       <PRODNR>3456</PRODNR>
       <PRODNM>KEYBOARD</PRODNM>
       <ACCNAME>WILLIAM</ACCNAME>
       <NRDOC>0003</NRDOC>
    </PRODUCT>
    <PRODUCT>
       <SERIAL>456DEF</SERIAL>
       <PRODNR>4567</PRODNR>
       <PRODNM>MOUSE</PRODNM>
       <ACCNAME>MARCUS</ACCNAME>
       <NRDOC>0004</NRDOC>
    </PRODUCT>
</CATALOG>

This snippet shows the progress of my current code:

getProductBySerialNumber(url) {
var serialNumber = document.getElementById('searchBox').value;
var xmlhttp;
var txt, xx, x, i;

if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
} else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        txt = "<table border='1'><tr><th>Product number</th><th>Product name</th><th>Account name</th><th>Document number</th></tr>";
        x = xmlhttp.responseXML.documentElement.getElementsByTagName("PRODUCT");

        for (i = 0; i < x.length; i++) {
            txt = txt + "<tr>";
            
            // Code logic to populate table rows goes here

            txt = txt + "</tr>";
        }
        
        txt = txt + "</table>";
        document.getElementById('showTable').innerHTML = txt;
    }
}

xmlhttp.open("GET", url, true);
xmlhttp.send();

}

Answer №1

To extract the necessary PRODUCT node, I recommend using XPath:

let path = '//SERIAL[text()="' + serialNumber + '"]/..';
let result = document.evaluate(path, xmlhttp.responseXML.documentElement, null, 9, null).singleNodeValue;

Please note: (document.selectNodes(xpath) is for IE browsers)

Check out this demo: http://example.com/demo

Alternatively, you could iterate through all PRODUCT nodes and identify the one with the matching search ID.

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

What could be causing my array to update when the method is called live but not during unit tests?

One of my methods is called toggleSelect which adds and removes items from an array named selectedItems. This method functions perfectly when I test it live in the browser. However, when running unit tests, it does not seem to work as expected. Despite cal ...

What's the best way to ensure my side navigation floats on top of my full-width slider?

I am currently working on implementing my side navigation to overlay on top of my full-width slider at the beginning of the webpage. However, when I add the slider, the navigation buttons in my side nav become unclickable. I have tried using the z-index ...

The function Amplify.configure does not exist

Currently attempting to utilize AWS Amplify with S3 Storage, following the steps outlined in this tutorial for manual setup. I have created a file named amplify-test.js, and here is its content: // import Amplify from 'aws-amplify'; var Amplify ...

Optimizing the position of smart info windows in Google Maps

I am facing a challenge while attempting to switch the infowindow in Google maps to the smartinfowindow, as the position of the infowindow appears incorrect. This issue only occurs with the smartinfowindow and not with the standard infowindow. Upon furthe ...

Achieving the n-th element from a JavaScript array

I have a project where I need to iterate through a JavaScript list by index, retrieve both the name and value of each item, and then perform a specific action with that information. The list is structured as follows: {"test-item-1": false, " ...

Python Selenium scraping script encountered an issue: Javascript element could not be located

I'm currently practicing my skills in scraping Javascript frontend websites and decided to work on the following site: While attempting to locate two elements using their xPath, I encountered an issue. The first element, the title, I was able to find ...

How to use hooks in NETXJS to pass data from a page to a component

Hey there, how are you doing? I am currently working on a project using Next.js and styled components. I am trying to change a string using props in my layout component, where the main content is dynamic per page. Page 'prueba.js' import React f ...

The <br/> tag is not functioning properly when retrieving text from a MySQL query

Currently, I am involved in a project that involves an A.I pushing text onto a MySQL database. Our goal is to display the ongoing writing process on a webpage. We are still actively working on this. We are retrieving the data and regularly checking the da ...

Having trouble getting a JS file to work with the Laravel Inertia.js and Vue.js3 template

Just getting started with inertia.js and facing an issue. My CSS styles are being applied, but my JavaScript file isn't functioning as expected. I'm working on an admin dashboard using Laravel 9 and vue.js-3 with a custom HTML template. Interes ...

Randomize elements with the click of a button

Every time the page refreshes, the words shuffle around. For instance, "May I# know# your name?" shuffles to "know May I your name". To display the correct sentence with "#" as "May I know your name?", click the SHUFFLE button to trigger the shuffling. HT ...

Transmit information to the controller using jQuery in a C# MVC environment

Here is my jQuery script code snippet. The script works perfectly and stores the data array/object in a variable called dataBLL. var dataBLL = []; $('#mytable tr').each(function (i) { dataBLL.push({ id: $(this).find('td:eq(0)').text( ...

Guide to sending a post request in Node.js using Mongoose

I recently tried to follow a tutorial (https://medium.com/weekly-webtips/building-restful-apis-with-node-js-and-express-a9f648219f5b) from 2 years ago to build an API. However, I'm struggling to update the code to work with more recent changes in the ...

Using THREE.js to animate objects and have them settle onto a specific face

I'm currently working on adding pins to a curved map of the US, but I'm facing some challenges. Right now, I'm using mathematical calculations to determine their distance from the highest part of the curve and adjust their height accordingly ...

Can you help me navigate through the router dom v6 to match product IDs from the API?

How do I display a specific product when it's clicked on based on its id from a Django Rest Framework API? I was previously using match from React Router DOM v5, but I'm not sure how to achieve the same functionality since match doesn't exis ...

What is the best way to align an object's rotation with a Vive controller's rotation when the trigger is pulled in A-Frame?

Exploring the possibilities of creating A-Frame applications, I decided to dive into the world of A-Frame Dominoes. In my current project, objects are spawned in response to the Vive trigger being pressed. While I have successfully managed to align the po ...

Safari encountering parsing date error

My Angular application is receiving date formats from a web service in the following format: myDate = "2020-03-05T08:00:00" This translates to the fifth of March, 2020 for me For Chrome, Firefox, and IE, the format is yyyy-mm-ddThh:mm:ss However, Safar ...

Issue with Zebra_Calendar and JSON compatibility in Internet Explorer 7

I have integrated the Zebra_Calendar jQuery plugin on my website, but encountered an issue when including a JSON implementation. Specifically, I am facing an "Object Doesn't Support This Property or Method" error related to string.split during initial ...

What is the best way to automatically scroll to the bottom of a modal after making a request and

I've been faced with a challenge regarding an online chat widget. My goal is to automatically scroll the widget down to display the latest message when a specific chat is opened. Despite using an async function, I encountered difficulties in achieving ...

Is it possible to initially design a login page using HTML/CSS and JavaScript, and then integrate VUE into it?

As part of a school project, I am tasked with developing a web-based application for a library system. The goal is to create a platform where librarians can login and manage books by adding, removing, or editing them. My responsibility lies in handling the ...

Plugin refresh after callback

I have a webpage that features a row of buttons at the top, followed by some content below. Whenever one of the buttons is clicked, the content is updated using UpdatePanels. Within this content, I am attempting to incorporate the royal slider plugin, wh ...