Reputation: 3715
My JavaScript code is making an Ajax call to retrieve a XML document and I'm having a hard time extracting a specific node from the result.
The XML returned is essentially a collection of key/value pairs and I want to extract the value for a given key. For the sake of this discussion, let's assume the returned XML looks like this:
<result>
<keyvaluepair>
<key>aaa</key>
<value>1234</value>
</keyvaluepair>
<keyvaluepair>
<key>bbb</key>
<value>5678</value>
</keyvaluepair>
</result>
and my Ajax call looks like this:
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",
processData: false,
url: "MyPage.aspx",
success: function (data, textStatus, xhr)
{
var myValue = parseInt($("???", data).text());
}
);
What would be the appropriate way to find the value associated with a given key, say "bbb"?
Upvotes: 1
Views: 67
Reputation: 93551
JQuery also parses XML so something like this should help:
success: function (data, textStatus, xhr)
{
var myValue = $(data).find('key[value="bbb"]').next('value').text();
}
turns out [value=]
won't work here, so use :contains
for unique values or a filter
to exactly match trimmed text content:
Example using contains
: http://jsfiddle.net/TrueBlueAussie/uhramdmx/
Or better yet, filter
: http://jsfiddle.net/TrueBlueAussie/uhramdmx/2/
var myValue = $(data).find('key').filter(function(){
return $.trim($(this).text()) == 'bbb';
}).next('value').text();
Upvotes: 2