tags:

views:

219

answers:

2

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!

+2  A: 

It's case sensitive, use "Table" like this:

$(xml).find("Table").each(function() {
  var stateName = $(this).find("StateLongName").text();
  var stateCode = $(this).find("StateShortName").text();
});

Update: Sorry this one was a bit baffling, don't use <table>, it treats it as html creating a <tbody> and things get stranger from there:) If you changed it to just abut anything else, it'll work, here's an example with it changed to <tabl>: http://jsfiddle.net/Yvetc/

Here's a full bare test page:

<html>
  <head>    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
    <script type="text/javascript">
    var xml="<NewDataSet><Tabl><stateLongName>Alabama</stateLongName><stateShortName>AL</StateShortName></Tabl><Tabl><StateLongName>Alaska</StateLongName><StateShortName>AK</StateShortName></Tabl></NewDataSet>";
    $(xml).find("Tabl").each(function() {
      var stateName = $(this).find("StateLongName").text();
      var stateCode = $(this).find("StateShortName").text();
      alert("State: " + stateName + " Code: " + stateCode);
    });
    </script>
  </head>
  <body>
  </body>
</html>
Nick Craver
I like to define `var $this = $(this)` when using that value more than once.
Matt Ball
Thanks for the quick response Nick. Unfortunately, changing the case still did not find any matches.
darryl
It appears that case sensitivity does NOT apply to the .find() method.Any case version of $(xml).find("statelongname") will match, while any character case version of $(xml).find("table") will NOT match.
darryl
@darryl - I found the glitch, see the updated answer :)
Nick Craver
is this behavior browser specific? Nick's original example works for me at http://jsfiddle.net/k9yfa/ on Chrome.
Anurag
@Anurag - It works because I changed the xml to not contain `<table>` but rather `<tabl>`, which seemed to mess things up quite a bit in the document fragment.
Nick Craver
@Nick, The difference was I was using a DOMParser to construct the DOM. jQuery tries to append to DOM to get the nodes, which relies on HTML as a host.
Anurag
Still doesn't work. Nick, you example seems to work in your tool, but not in a bare html page. I can copy the code entirely and put it in a empty html page with a reference to jQuery and it does not work. I tried to post the code here, unfortunatately Stack Overflow won't allow it. It looks like I would need to ask another question to show the code. Ahhggrrr, very frustrating!
darryl
Just as a bit of background info... I'm trying to pull a Country and State list from some internal webservices that return a .Net DataSet. I was calling the web services directly from the browser with $.ajax. However, this only worked in IE. I'm not sure why, but it seemed to have something to do with authentication/cross-domain issues. Anyway, now I'm calling a PageMethod in the code behind and returning dsStates.GetXml(), dsStates is a .Net DataSet. That's why the xml is in the format it is in.
darryl
@darryl - I'm not sure what to tell you, I can't reproduce your trouble after changing the `<table>` tag. I updated the bare test case page I also have working here, does that still not work for you?
Nick Craver
It seems to be a browser issue. I created a bare test page from the code you provided. It works in Firefox 3.6.2 and Chrome 4.1.249.1042 (42199), but not IE 8.0.6001.18702. I'm running XP Pro. That's disappointing, one of the beauties of jQuery is supposed to be cross browser compatibility. I've been waiting for true browser compatibility since '95, oh well, enough whining.
darryl
+1  A: 
$.ajax({
             type: "GET",
             url: "labels.xml",
             dataType: "xml",
             success: function(xml) {
                 $(xml).find('label').each(function(){
                     var id_text = $(this).attr('id')
                     var name_text = $(this).find('name').text()

                     $('<li></li>')
                         .html(name_text + ' (' + id_text + ')')
                         .appendTo('#update-target ol');
                 }); //close each(
             }
         }); //close $.ajax(

sample xml for this:

<?xml version="1.0" encoding="iso-8859-1"?>


<labels>
   <label id='ep' added="2003-06-10">
     <name>Ezra Pound</name>
     <address>
       <street>45 Usura Place</street>
       <city>Hailey</city>
       <province>ID</province>
     </address>
   </label>
   <label id='tse' added="2003-06-20">
     <name>Thomas Eliot</name>
     <address>
       <street>3 Prufrock Lane</street>
       <city>Stamford</city>
       <province>CT</province>
     </address>
   </label>
   <label id="lh" added="2004-11-01">
     <name>Langston Hughes</name>
     <address>
       <street>10 Bridge Tunnel</street>
       <city>Harlem</city>
       <province>NY</province>
     </address>
   </label>
   <label id="co" added="2004-11-15">
     <name>Christopher Okigbo</name>
     <address>
       <street>7 Heaven's Gate</street>
       <city>Idoto</city>
       <province>Anambra</province>
     </address>
   </label>
 </labels>
XGreen