开发者

Traversing all nodes of an XML doc with jQuery

How would I traverse an XML doc of unknown structure, so as 开发者_StackOverflow社区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.


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


<script>
var xml = "<xml></xml>";
$("#xml").html(xml);
</script>
<div id="xml"></div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜