0

I have an xml string that I need to pull a value from using only JavaScript. Here's an example of the xml string:

<RequestVars>
    <BuyerCookie>O7CPHFP7AOY</BuyerCookie>
    <Extrinsic name="CostCenter">670</Extrinsic>
    <Extrinsic name="UniqueName">catalog_tester</Extrinsic>
    <Extrinsic name="UserEmail">catalog_tester@mailinator.com</Extrinsic>
</RequestVars>

And I need to get the email address from it (i.e. catalog_tester@mailinator.com). I have a way to pull the value for a given unique element, such as getting O7CPHFP7AOY for BuyerCookie using this function:

function elementValue(xml, elem) {
    var begidx;
    var endidx;
    var retStr;

    begidx = xml.indexOf(elem);
    if (begidx > 0) {
        endidx = xml.indexOf('</', begidx);
        if (endidx > 0)
            retStr = xml.slice(begidx + elem.length,
 endidx);
        return retStr;
    }
    return null;
}

But now, I need a way to look up the value for the "Extrinsic" element with the value "UserEmail" for attribute "name". I've seen a couple ways to accomplish this in JQuery but none in JavaScript. Unfortunately, for my purposes, I can only use JavaScript. Any ideas?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Rob
  • 897
  • 3
  • 8
  • 22

1 Answers1

0

I came up with a solution. It's a little messy, but it does the tricky. I feed in the string representation of the xml, the name of the element tag I'm looking for, the name of the attribute and the attribute value I am seeking an element value for.

function elementValueByAttribute(xml, elem, attrName, attrValue) {
    var startingAt = 1;
    var begidx;
    var mid1idx;
    var mid2idx;
    var endidx;
    var aName;
    var retStr;
    var keepGoingFlag = 1;

    var count = 0;
    while (keepGoingFlag > 0) {
        count++;
        begidx = xml.indexOf(elem, startingAt);
        if (begidx > 0) {
            mid1idx = xml.indexOf(attrName, begidx);
            if (mid1idx > 0) {
                mid2idx = xml.indexOf(">", mid1idx);
                if (mid2idx > 0) {
                    aName = xml.slice(mid1idx + attrName.length + 2, mid2idx - 1);
                    if (aName == attrValue) {
                        endidx = xml.indexOf('</', begidx);
                        if (endidx > 0)
                        {
                            retStr = xml.slice(mid2idx + 1, endidx);
                        }
                        return retStr;
                    }
                }
            }
        }
        if (startingAt == mid2idx) {
            keepGoingFlag = 0;
        } else {
            startingAt = mid2idx;
        }
    }
    return null;
}
Rob
  • 897
  • 3
  • 8
  • 22