From MozillaZine Knowledge Base

(Difference between revisions)

Revision as of 07:14, 8 March 2005

XPath Expressions

The following function can be used to apply Path expressions to XML documents. The first argument is a DOM object, while the second is a stringified XPath expression.

function evalaute(aXmlDoc, aXpath) {
  // evaluate an XPath expression against a Document object, returning the results as an array
  // thanks wanderingstan at morethanwarm dot mail dot com

  var xpe = new XPathEvaluator();
  var found = new Array();
  var result = xpe.evaluate(aXpath, aXmlDoc, xpe.createNSResolver(aXmlDoc.documentElement), 0, null);
  while (res = result.iterateNext())
  return found;

Sample Usage

Assume we have the following XML document in a DOM tree:

<?xml version="1.0"?>
  <person first-name="eric" middle-initial="H" last-name="jung">
    <address street="321 south st" city="denver" state="co" country="usa"/>
    <address street="123 main st" city="arlington" state="ma" country="usa"/>

  <person first-name="jed" last-name="brown">
    <address street="321 north st" city="atlanta" state="ga" country="usa"/>
    <address street="123 west st" city="seattle" state="wa" country="usa"/>
    <address street="321 south avenue" city="denver" state="co" country="usa"/>

You can now "query" the document with XPath expressions. Although walking the DOM tree can achieve similar results, using XPath expressions is much quicker and more powerful. If you can rely on id attributes, document.getElementById() is still powerful, but it's not nearly as powerful as XPath. Here are some examples.

// display the last names of all people in the doc
var results = evaluate(fileContents, "//person/@last-name");
for (var i=0; i<results.length; i++)
  alert("Person #" + i + " has the last name " + results[i]);

// get the 2nd person node
results = evaluate(fileContents, "/people/person[2]");

// get all the person nodes that have addresses in denver
results = evaluate(fileContents, "//person[address/@city='denver']);

//get all the addresses that have "south" in the street name
results = evaluate(fileContents,  "//address[contains(@street, 'south')]");