0

How would I traverse an XML doc of unknown structure, so as to perform an operation on every node, using jQuery?

I'm looking for some sort of recursive function whereby I could access each node, check for sub-nodes, and repeat.

Yarin
  • 173,523
  • 149
  • 402
  • 512
  • Yarin: Would [this](http://stackoverflow.com/questions/1574113/looping-through-xml-with-jquery) be your answer? Edit: See user meder's answer for nodes with unspecified depth or titles. – ericb Jun 22 '11 at 23:15
  • Agreed! +1 to maenu. – ericb Jun 23 '11 at 00:34
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Fabio Antunes Mar 11 '14 at 18:43

2 Answers2

4

What you are looking for is basically a depth-first-search. You could do something like this:

var depthFirstTraversal = function($root, callback) {
    $root.children().each(function() {
        depthFirstTraversal($(this), callback);
    });
    callback($root);
};
depthFirstTraversal($(selector), function($node) {
    // do stuff with $node
});

Edit: Made a fiddle here

Yarin
  • 173,523
  • 149
  • 402
  • 512
Manuel Leuenberger
  • 2,327
  • 3
  • 21
  • 27
0
<script>
var xml = "<xml></xml>";
$("#xml").html(xml);
</script>
<div id="xml"></div>
Doug Molineux
  • 12,283
  • 25
  • 92
  • 144
  • @Peter- My question was ill-put- See my edit: I need to be able to access each individual node, not just dump the whole thing into html – Yarin Jun 22 '11 at 21:55