如何使用jQuery.parseXML()从XML解析和获取特定的属性?

时间:2015-09-01 06:19:30

标签: jquery xml parsexml

我有一个像

这样的XML字符串
var pid = // should be fetched from ProductcfgPath attribute
var sku = // should be fetched from SKUID attribute

alert(pid);  // 176
alert(sku);  // TWS090

我需要输出

function firstHit() {
    return new Promise(function(resolve, reject) {
        var missCntr = 0, missQty = 2;

        function checkResult(err, val) {
            if (err || !val) {
                // see if all requests failed
                ++missCntr;
                if (missCntr === missQty) {
                    reject();
                }
            } else {
                resolve(val);
            }
        }
        request(opts,function(err, response, body){
            checkResult(err, body.result.hit);
        }

        client.get("some_key", function(err, reply) {
            checkResult(err, reply.result.hit);
        });
    });
}

firstHit().then(function(hit) {
    // one of them succeeded here
}, function() {
    // neither succeeded here
});

1 个答案:

答案 0 :(得分:0)

解决了它

var rawXmlString = '\<\?xml version = "1.0" encoding = "UTF-8" ?><ProductDetails ProductID="TuscanWengeShoeRack010cfg" ProductcfgPath="http://localhost/media/productattachment/176/TuscanWengeShoeRack010cfg.xml" SKUID="TWS090" />';
var $xmlJSObject = $.parseXML(rawXmlString);
var path = $($xmlJSObject).find('ProductDetails').attr('ProductcfgPath');
var sku = $($xmlJSObject).find('ProductDetails').attr('SKUID');

var numberArray = path.match(/(\d+)/g);
var pid = numberArray[0];

alert(pid);  // 176
alert(sku);  // TWS090