How to find/extract data from xml with jQuery
Posted
by darryl
on Stack Overflow
See other posts from Stack Overflow
or by darryl
Published on 2010-04-01T19:27:48Z
Indexed on
2010/04/01
19:33 UTC
Read the original article
Hit count: 312
I'm trying to extract the StateLongName and StateShortName values from the xml below.
I know there has to be a simple elegant way to do this with jQuery.
<NewDataSet>
<Table>
<StateLongName>Alabama</StateLongName>
<StateShortName>AL</StateShortName>
</Table>
<Table>
<StateLongName>Alaska</StateLongName>
<StateShortName>AK</StateShortName>
</Table>
...elments removed for brevity
</NewDataSet>
Here's what I've tried.
Load the xml from above into a Javascript variable name xml.
Try #1
$(xml).find("TABLE").each(function()
{
var stateName = $(this).find("StateLongName").innerText;
var stateCode = $(this).find("StateShortName").innerText;
});
Try #1 doesn't find anything and never goes inside to load the stateName and stateCode variables.
Try #2
$(xml).find("StateLongName").each(function()
{
var stateName = $(this).find("StateLongName").innerText;
var stateCode = $(this).find("StateShortName").innerText;
});
Try #2 does find matches, however the stateName and stateCode are left undefined.
Try #3
$(xml).find("StateLongName").each(function()
{
var stateName = $($(xml).find('StateLongName').parent()[0].innerHTML)[1].data;
var stateCode = $($(xml).find('StateLongName').parent()[0].innerHTML)[5].data;
});
Try #3 works but there has to be a better way. Please enlighten me.
Thanks for you time!
© Stack Overflow or respective owner