Jump to content

Accessing value of nodes under a specific node only, using javascript


Peeyush

Recommended Posts

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 by Peeyush
  • Like 2
Link to comment
Share on other sites

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

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...