How to parse XML using jQuery?

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

  <Page Name="test">
      <test>this is a test.</test>
  <Page Name = "User">

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

There is the $.parseXML function for this:

You can use it like this:

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


If you really want an object, you need a plugin for that. This plugin for instance, will convert your XML to JSON:

you can use .parseXML

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


    xmlDoc = $.parseXML( xml ),
    $xml = $( xmlDoc );

here is the fiddle

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

    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.

$xml = $( $.parseXML( xml ) );

    // elem = found XML element

Have a look at jQuery's .parseXML() [docs]:

var $xml = $(jQuery.parseXML(xml));

var $test = $xml.find('Page[Name="test"] > controls > test');

I went the way of jQuery's .parseXML() however found that the XML path syntax of 'Page[Name="test"] > controls > test' wouldn't work (if anyone knows why please shout out!).

Instead I chained together the individual .find() results into something that looked like this:


The result achieves the same as what I would expect the one shot find.

First thing that pop-up in google results There's no simple way to access xml structure (like you described Pages->pagename->controls->test) in jQuery without any plugins.