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">[email protected]</Extrinsic>
</RequestVars>

And I need to get the email address from it (i.e. [email protected]). 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?

2
  • nope, that doesn't seem to help Commented Oct 1, 2013 at 21:12
  • Don't parse XML as a string. Ever. Commented Oct 2, 2013 at 6:08

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.