javascriptxsltwebview2

How to get the value of a XML node which has a specific attribute value using JavaScript?


I have this XML file (stripped down):

<?xml version="1.0" encoding="UTF-8"?>
<Labels Version="24100002">
    <Attendant>Attendant</Attendant>
    <Attendant Index="1">Car Park Attendant</Attendant>
    <Attendant Index="2">Entrance Attendant</Attendant>
    <Attendant Index="3">Auditorium Attendant</Attendant>
    <Attendant Index="4">Attendant 4</Attendant>
</Labels>

And, I have this JavaScript for loading a file:

function loadXMLDoc(filename) {
    return fetch(filename)
        .then(response => {
            if (!response.ok) {
            throw new Error('Network response was not ok');
            }
            return response.text();
        })
        .then(str => (new window.DOMParser()).parseFromString(str, "text/xml"))
        .catch(error => {
            console.error('There has been a problem with your fetch operation:', error);
        });
}

In my HTML file I am doing this (stripped down):

// Code snipped

// Fetch the XML and XSL files asynchronously
var [xsl, xml, labelsInfo] = await Promise.all([
    loadXMLDoc('DutyHistory-transform.xsl'),
    loadXMLDoc('DutyAssignHistory.xml'),
    loadXMLDoc('LabelsInfo.XML')
]);

// Code snipped

// We have to add 1 to the indexing because the LabelsInfo file has a "Attendant" label too!
xsltProcessor.setParameter(null, 'index13', labelsInfo.documentElement.getElementsByTagName('Attendant')[1].textContent.trim());
xsltProcessor.setParameter(null, 'index14', labelsInfo.documentElement.getElementsByTagName('Attendant')[2].textContent.trim());
xsltProcessor.setParameter(null, 'index15', labelsInfo.documentElement.getElementsByTagName('Attendant')[3].textContent.trim());

Is there any way that I can directly get the required Attendant values where they have a @Index attribute? At the moment I incremented by 1 as you can see. Which works fine. Just wondered if I can avoid that?

My environment is WebView2.


Solution

  • I have come upon with this solution, based on the provided answer and the comment to my question:

    xsltProcessor.setParameter(null, 'index13', labelsInfo.documentElement.querySelectorAll("Attendant[Index='1']")[0].textContent);
    xsltProcessor.setParameter(null, 'index14', labelsInfo.documentElement.querySelectorAll("Attendant[Index='2']")[0].textContent);
    xsltProcessor.setParameter(null, 'index15', labelsInfo.documentElement.querySelectorAll("Attendant[Index='3']")[0].textContent);