Reputation: 1691
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
?
Upvotes: 40
Views: 157973
Reputation: 3034
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/
Upvotes: 42
Reputation: 9575
$xml = $( $.parseXML( xml ) );
$xml.find("<<your_xml_tag_name>>").each(function(index,elem){
// elem = found XML element
});
Upvotes: 10
Reputation: 131
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:
$xmlDoc.find('Page[Name="test"]')
.find('contols')
.find('test')
The result achieves the same as what I would expect the one shot find.
Upvotes: 1
Reputation: 27770
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.
Upvotes: 15
Reputation: 31043
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/
Upvotes: 19
Reputation: 817120
Have a look at jQuery's .parseXML()
[docs]:
var $xml = $(jQuery.parseXML(xml));
var $test = $xml.find('Page[Name="test"] > controls > test');
Upvotes: 2
Reputation: 16981
First thing that pop-up in google results http://think2loud.com/224-reading-xml-with-jquery/ There's no simple way to access xml structure (like you described Pages->pagename->controls->test) in jQuery without any plugins.
Upvotes: 0