Peeyush Posted May 11, 2012 Share Posted May 11, 2012 (edited) Xml code is something like this <kids> <dennis> <age> 6 </age> <weight> 10 </weight> </dennis> <john> <age> 8 </age> <weight> 20 </weight> </john></kids><adults> <tom> <age> 36 </age> <weight> 110 </weight> </tom> <kramer> <age> 80 </age> <weight> 67 </weight> </kramer></adults> now i know how to access all the ages in the document, suppose i need to access the ages of only children, or only adults how will i do it using javascript? Edited May 11, 2012 by Peeyush 2 Link to comment Share on other sites More sharing options...
boen_robot Posted May 13, 2012 Share Posted May 13, 2012 The easiest way is to use XPath, but browsers have different ways of letting you use it. It's easiest if you use a library that abstracts away those differences. For example, using Sarissa, you can do it like: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Sarissa XPath example</title> </head> <body> <button id="testButton">test xpath</button> <script type="text/javascript" src="sarissa.js"></script> <script type="text/javascript" src="sarissa_ieemu_xpath.js"></script> <script type="text/javascript"> //<![CDATA[ document.getElementById('testButton').onclick = function() { var xmldoc = new XMLHttpRequest(); xmldoc.open('GET', 'test.xml', false); xmldoc.send(null); xmldoc = xmldoc.responseXML; xmldoc.setProperty("SelectionLanguage", "XPath"); var result = xmldoc.selectNodes('//age[.<18]'); for (var i=0, l = result.length; i<l; ++i) { alert(result[i].nodeValue); } } //]]> </script> </body> </html> Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now