Nemesis Nemesis - 10 days ago 5
Javascript Question

Extract attribute value depending on two others

I have the following xml:

<response>
<result-code fatal="false">0</result-code>
<lgt from="100" lgt="5.37828" to="644"/>
<lgt from="100" lgt="354.634640124" to="756"/>
</response>


How to find and parse lgt attribute value depending on from and to attribute's value using javascript?

Answer

firstly, parse the xml string into an xmlDoc (assuming you aren't using xmlHttpRequest responseXML - skip the conversion in that case)

var str = '<response><result-code fatal="false">0</result-code><lgt from="100" lgt="5.37828" to="644"/><lgt from="100" lgt="354.634640124" to="756"/></response>';

var xmlDoc = (new DOMParser()).parseFromString(str, "text/xml");

at least in firefox/chrome you can use the following -

function parseLGT(from, to) {
    var x = xmlDoc.querySelector('lgt[from="' + from + '"][to="' + to + '"]');
    return x && x.getAttribute('lgt')
};
console.log(parseLGT(100,644));

IE/Edge - I haven't tested