tags:

views:

1797

answers:

4

I am getting some XML back from an AJAX call (no surprise) and I want to do something but only on certain nodes and something else on the rest. For example

<xml>
  <node name="x">
  </node>
  <node name="x">
  </node>
  <node name="y">
  </node>
  <node name="z">
  </node>
</xml>

I want all the nodes with name x to go to one table and I want all the others to go to another table.

+1  A: 

You can use xpath in jQuery to select the nodes:

$("//node[@name='x']")

http://docs.jquery.com/DOM/Traversing/Selectors

Fiona Holder
+1 - Very sleek second answer :)
karim79
Thank working so far. But how do I do the not part?
uriDium
The xpath syntax has been deprecated in jQuery 1.2 and doesn't work at all anymore in 1.3, see the attribute section on this page here: http://docs.jquery.com/Selectors
Martijn Pieters
+1  A: 

jQuery accepts xpath expressions as well.

$('node[name="x"]')

will select all the nodes named "node" with an attribute of "name" that has the value "x"

ScottSEA
So far so good. My xpath is terrible. How do I alter it to select where everything is NOT for name=x.
uriDium
$('node[name][not(name="x"]')will find all nodes with names not equal to 'x'
ScottSEA
+1  A: 
success: function(xml) {
   $(xml.find('node').each(function(){
    if($(this).attr('name')=='x') {
       //go to one table
    } else {
       //go to another table
    }

   }
}
Daniel Moura
+3  A: 

Use an attribute filter, in particular the attributeEquals filter:

$("node[name='x']");

To select all the other nodes, use the attributeNotEquals filter:

$("node[name!='x']");

You can then apply jQuery manipulations to move these nodes elsewhere.

Note that XPath-style selectors where deprecated in version 1.2, and have been removed altogether in jQuery 1.3.

If you can influence what the server sends, you may want to switch to using JSON instead, you may find it easier to parse.

Martijn Pieters