Nemesis Nemesis - 1 year ago 76
Javascript Question

Extract attribute value depending on two others

I have the following xml:

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

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

Answer Source

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')

IE/Edge - I haven't tested

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download