How to parse XML using jQuery? How to parse XML using jQuery? xml xml

How to parse XML using jQuery?


There is the $.parseXML function for this: http://api.jquery.com/jQuery.parseXML/

You can use it like this:

var xml = $.parseXML(yourfile.xml),  $xml = $( xml ),  $test = $xml.find('test');console.log($test.text());

If you really want an object, you need a plugin for that. This plugin for instance, will convert your XML to JSON: http://www.fyneworks.com/jquery/xml-to-json/


you can use .parseXML

var xml='<Pages>          <Page Name="test">           <controls>              <test>this is a test.</test>           </controls>            </Page>          <page Name = "User">           <controls>             <name>Sunil</name>           </controls>          </page>        </Pages>';

jquery

    xmlDoc = $.parseXML( xml ),    $xml = $( xmlDoc );    $($xml).each(function(){       alert($(this).find("Page[Name]>controls>name").text());     });

here is the fiddle http://jsfiddle.net/R37mC/1/


I assume you are loading the XML from an external file. With $.ajax(), it's quite simple actually:

$.ajax({    url: 'xmlfile.xml',    dataType: 'xml',    success: function(data){        // Extract relevant data from XML        var xml_node = $('Pages',data);        console.log( xml_node.find('Page[Name="test"] > controls > test').text() );    },    error: function(data){        console.log('Error loading XML data');    }});

Also, you should be consistent about the XML node naming. You have both lowercase and capitalized node names (<Page> versus <page>) which can be confusing when you try to use XML tree selectors.