1

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"?

1 Answer 1

2

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

1 Comment

thank you for the suggestion. As you pointed out, "[value=]" did not work but ":contains" achieves the same result. Using a combination of 'find' and 'next' works very well and give me the result I was looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.