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?

4

1 回答 1

0

我想出了一个解决方案。这有点混乱,但它确实很棘手。我输入了 xml 的字符串表示形式、我正在寻找的元素标记的名称、属性的名称以及我正在为其寻找元素值的属性值。

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;
}
于 2013-10-01T21:28:57.073 回答