views:

25

answers:

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  A: 

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 :)

Nick Craver
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!
RyanPitts
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
@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.
Nick Craver
great...thanks for the help, Nick!
RyanPitts