bit my byte
Parsing XML with jQuery.parseXML method
Web developers are all accustomed to use the XML format as one of their preferred formats when retrieving the results of an AJAX request. Although in the last years the JSON format has gained its momentum in AJAX, the XML format remains a valid option when you need to get structured and complex data. But how jQuery parses XML? Simply put, it uses its private method called parseXML().
jQuery.parseXML() was added to jQuery in v1.5. If you can, upgrade to the latest to use it. If you can’t, if you have to use an out-dated version, you can easily add the function to your own script. Unlike many parts of jQuery, it’s nicely self-contained in the jQuery source:
This method has the following implementation:
// Cross-browser xml parsing
// (xml & tmp used internally)
parseXML: function( data , xml , tmp ) {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
tmp = xml.documentElement;
if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
}
As with many jQuery’s methods, the W3C DOM procedure is tried first, in this case using the DOMParser feature. Since some versions of Internet Explorer don’t support this procedure, an alternate method is tried by using an ActiveX object. If everything goes fine and the XML document passed to this method as a string is a valid XML document (that is, it’s well-formed), then the XML document itself is returned. Otherwise, jQuery triggers and error and sends it to the JavaScript console.
I pulled this example from the jQuery docs http://api.jquery.com/jQuery.parseXML/
Try changing node values, they are updated in the jQuery object!
var container = $( document.body );
var xml = '<rss version="2.0"><channel><title>RSS Title</title></channel></rss>',
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$title = $xml.find( 'title' );
// append "RSS Title" to #someElement
container.append( $("<p/>", { "text" : $title.text() }) );
// change the title to "XML Title"
$title.text( 'XML Title' );
// append "XML Title" to #anotherElement
container.append( $("<p/>", { "text" : $title.text() }) );
// also changed in $xml jQuery obj
container.append( $("<p/>", { "text" : "$xml > title also = " + $xml.find( 'title' ).text() }) );
| Print article | This entry was posted by baris aydinoglu on 2011/04/14 at 19:51, and is filed under JavaScript, jQuery, XML. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |

