Search code examples
jqueryxmlparsexml

Parsing XML in jQuery with/out parseXML?


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


Solution

  • 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.