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

About this user

James Robertson http://www.r0bertson.co.uk

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Using XPath in JavaScript (Mozilla based)

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)
<codes>
  <codex value='bQ' index='Q'/>
  <codex value='S' index='R'/>
  <codex value='PU' index='S'/>
  <codex value='ji' index='T'/>
  <codex value='0' index='U'/>
  <codex value='33' index='V'/>
  <codex value='A' index='W'/>
  <codex value='tO' index='X'/>
  <codex value='fW' index='Y'/>
  <codex value='P' index='Z'/>
  <codex value='4h' index='a'/>
  <codex value='B' index='b'/>
  <codex value='m' index='c'/>
  <codex value='qf' index='d'/>
  <codex value='uJ' index='e'/>
</codes>


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


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


see also: Reading an XML file using JavaScript
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS