1

I am trying to get the value of an attribute of an XML node and set it as a variable using JQuery. Is this possible?

<DataContainer>
    <Customers>
        <Customer customerId="7366" customerName="Boardwalk Audi" url="" 
            address="5930 West Plano Pkwy" city="Plano" state="Texas" 
            zipCode="75093" latitude="33.0160690000000000" 
            longitude="-96.8268970000000000">
    <Customers>
<DataContainer>

I want to set the customerId attribute of 7366 as a variable for later use like below:

$customerId = customer id from xml node attribute;

Is this possible? Let me know if you need any more clarification. Thanks!

1
  • Thanks for editing this, Canavar. I always forget about the 4 space indent to make the readable code block. Commented Sep 14, 2010 at 21:43

1 Answer 1

1

If you're fetching the XML in an ajax request you can just use .find() to get the node and .attr() to get the attriute, for example:

var cust_id = $(xml).find("Customer").attr("customerId");

You can see an example here, keep in mind this is intended to be used in an ajax callback ultimately using responseXML (not just an XML string), but you get the idea :)

Sign up to request clarification or add additional context in comments.

3 Comments

Awesome, worked like a charm! I should've known to just use a selector. Thanks for the super quick help. And i love the link...i'll be using that a lot i'm sure!
Is there a way to combine variables if i am doing something similar to your code above. If i get the address, city, state, and zipCode values can i combine them into one variable that would output as "5930 West Plano Pkwy, Plano, Texas, 75093"? Thanks again!
@RyanPitts - Yeah you can get them all as variables or use a single string, e.g. var n = $(xml).find("Customer"); var output = n.attr("address") + ", " + n.attr("city") + ", " + n.attr("state") + ", " + n.attr("zipCode"); or take an array and .join(", ")...whatever method really, all the same approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.