Reputation: 14950
I have the following XML
<response>
<item>
<sku>83340</sku>
<vendor>83340</vendor>
<errors>
<msg>Real-Time Error</msg>
</errors>
</item>
<item>
<sku>83340</sku>
</item>
<item>
<sku>05319GS11007</sku>
<vendor>83340</vendor>
<errors>
<msg>Fatal Error</msg>
</errors>
</item>
</response>
Using JQUERY, I want to search for the items with ERRORs only and get the corresponding SKU.
I can find the item with errors but how can i get the corresponding SKU so that I can say that the SKU has an error:
var errors = '';
jQuery(res).find("errors").each(function ( i ) {
jQuery(this).find("msg").each(function () {
errors += ' - ' + jQuery(this).text(); + '\n'
});
});
something like this
jQuery(res).find("item").each(function ( i ) {
if(jQuery(this).has( "error" )){
var stSKU = jQuery(this).find("sku").text();
var stError = jQuery(this).find("msg").text();.each(function () {
errors += ' # SKU # 'stSKU ' - ' + stError + '\n'
});
}
});
Output will be like:
SKU # 83340 has Real Time Error.
SKU # 05319GS11007 has Fatal Error.
Thanks.
Upvotes: 1
Views: 40
Reputation: 10282
You can use jQuery.parseXML()
to parse any XML
.
For more read here
var xml = `<response>
<item>
<sku>83340</sku>
<vendor>83340</vendor>
<errors>
<msg>Real-Time Error</msg>
</errors>
</item>
<item>
<sku>83340</sku>
</item>
<item>
<sku>05319GS11007</sku>
<vendor>83340</vendor>
<errors>
<msg>Fatal Error</msg>
</errors>
</item>
</response>`;
var xmlObj = $.parseXML( xml );
var err;
$(xmlObj).find("item").each(function(item){
err = $(this).find("errors");
if(err.length){
console.log("SKU #" + $(this).find("sku").text() + " has " + $(err).find("msg").text());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Upvotes: 1