2

Both are working... so why do i need parseXML ?

var x='<a>\
<item k="1" p1="aaa" />\
<item k="2" p1="bbb" />\
</a>';


alert($($.parseXML(x)).find("item[k='1']").attr('p1')); //aaa

alert($(x).find("item[k='1']").attr('p1')); //aaa

http://jsbin.com/ukahum/2/edit

noob
  • 8,982
  • 4
  • 37
  • 65
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 1
    Did you look at the docs for $? – Dave Newton Apr 19 '12 at 13:18
  • [From the docs](http://api.jquery.com/jQuery/) > XML (data returned from an Ajax call) can be passed to the $() function so individual elements of the XML structure can be retrieved using .find() and other DOM traversal methods. – Manse Apr 19 '12 at 13:22
  • @ManseUK ok fine thanks. but why do i need parseXML if i have it already without it ...? – Royi Namir Apr 19 '12 at 13:23
  • parseXML returns an XMLDocument - $ returns a jquery object - they are different – Manse Apr 19 '12 at 13:27

1 Answers1

3

The $.parseXML function will use the DOMParser or something similar in IE.

So it will return an real xml object so it will contain things like for example the xml version ($.parseXML(xml).xmlVersion).

If you've got xml like this:

<?xml version="1.0" encoding="UTF-8" ?>
<ok>
    <yes>true</yes>
</ok>

and use you're second example you'll get this back:

[
<!--?xml version="1.0" encoding="UTF-8" ?-->
, 
<ok>​…​</ok>​
]

So if you try to execute $(xml).find("ok") now it wont find anything because ok is the parent tag and if you execute $(xml).first() you'll get an comment and I don't think that that will be nice.

but if you're using your first example you'll get a document as parent tag:

[#document]

so you can get the ok tag like this: $($($.parseXML(xml)).find("ok") without problems and there won't be a comment as first node.

noob
  • 8,982
  • 4
  • 37
  • 65