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
?
jQuery can be used for XML processing on the Web as well as HTML processing, and in this article I show some examples of this use.
The XML DOM (Document Object Model) defines the properties and methods for accessing and editing XML. However, before an XML document can be accessed, it must be loaded into an XML DOM object. All modern browsers have a built-in XML parser that can convert text into an XML DOM object.
jQuery parseXML() method The parseXML() method in jQuery is used to parse a string into an XML document. It uses native methods of the browser for creating a valid XML document. This valid XML document can be passed to jQuery for creating a jQuery object that can be manipulated or traversed.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With