jQuery XML – How to Parse XML Using jQuery

javascriptjqueryxml

How do I parse XML, and how can I navigate the result using jQuery? Here is my sample XML:

<Pages>
  <Page Name="test">
    <controls>
      <test>this is a test.</test>
    </controls>
  </Page>
  <Page Name = "User">
    <controls>
      <name>Sunil</name>
    </controls>
  </Page>
</Pages>

I would like to find the node by this path Pages -> Page Name -> controls -> test ?

Best Answer

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/