Jump to content

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


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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...