Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Using XPath in JavaScript (Mozilla based) (See related posts)

The following JavaScript code uses XPath to select a specific element. Note: This code works for Firefox, but Internet Explorer has it's own implementation of XPath. see Introduction to using XPath in JavaScript [mozilla.org]

doc (xml document)
   1  
   2  <codes>
   3    <codex value='bQ' index='Q'/>
   4    <codex value='S' index='R'/>
   5    <codex value='PU' index='S'/>
   6    <codex value='ji' index='T'/>
   7    <codex value='0' index='U'/>
   8    <codex value='33' index='V'/>
   9    <codex value='A' index='W'/>
  10    <codex value='tO' index='X'/>
  11    <codex value='fW' index='Y'/>
  12    <codex value='P' index='Z'/>
  13    <codex value='4h' index='a'/>
  14    <codex value='B' index='b'/>
  15    <codex value='m' index='c'/>
  16    <codex value='qf' index='d'/>
  17    <codex value='uJ' index='e'/>
  18  </codes>


Assuming the doc object below contains the XML data from above.
   1  
   2  var nodesSnapshot = doc.evaluate("codes/codex[@index='a']", doc, null, XPathResult.
   3    UNORDERED_NODE_SNAPSHOT_TYPE, null );
   4  node = nodesSnapshot.snapshotItem(0);
   5  msg = "The secret code for '" + node.getAttribute('index') + "' is " + node.getAttribute('value');
   6  alert(msg);


output (value from the alert box)
   1  
   2  "The secret code for 'a' is 4h"


see also: Reading an XML file using JavaScript

You need to create an account or log in to post comments to this site.


Click here to browse all 5545 code snippets

Related Posts