XPath: Difference between revisions

From MozillaZine Knowledge Base
Jump to navigationJump to search
m (added another resource + asqueella's footer)
No edit summary
Line 1: Line 1:
=XPath Expressions=
XPath is a language for addressing parts of an XML document. It is a [http://www.w3.org/TR/xpath W3C recommendation].
The following function can be used to apply XPath expressions to XML documents. The first argument is a DOM object, while the second is a stringified XPath expression.
 
This article describes Mozilla interfaces exposing XPath functionality to Javascript code. It doesn't teach XPath itself, if you're unfamiliar with this technology, please refer to [http://www.w3schools.com/xpath/ W3Schools XPath tutorial].
 
==Wrapper function==
The following function can be used to evaluate XPath expressions on given XML nodes. The first argument is a DOM node, while the second is a string defining an XPath expression.
 
Note that you shouldn't use this function if you expect to get a long list of results from it.


<pre>
<pre>
function evalaute(aXmlDoc, aXpath) {
// evaluate an XPath expression aExpression against a given DOM node aNode,  
  // evaluate an XPath expression against a Document object, returning the results as an array
// returning the results as an array
  // thanks wanderingstan at morethanwarm dot mail dot com
// thanks wanderingstan at morethanwarm dot mail dot com
 
function evaluateXPath(aNode, aExpr) {
   var xpe = new XPathEvaluator();
   var xpe = new XPathEvaluator();
  var found = new Array();
   var result = xpe.evaluate(aExpr, aNode, xpe.createNSResolver(aNode.ownerDocument.documentElement),
   var result = xpe.evaluate(aXpath, aXmlDoc, xpe.createNSResolver(aXmlDoc.documentElement), 0, null);
                            0, null);
  var found = [];
   while (res = result.iterateNext())
   while (res = result.iterateNext())
     found.push(res);
     found.push(res);
Line 17: Line 24:


==Sample Usage==
==Sample Usage==
 
Assume we have the following XML document (see also [[How to Create a DOM tree]] and [[Reading and Writing XML to and from DOM trees]]) and <code>people</code> is the <code><people></code> element:
Assume we have the following XML document in a DOM tree variable named '''fileContents''':


<pre>
<pre>
Line 36: Line 42:
</pre>
</pre>


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.
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 <code>id</code> attributes, <code>document.getElementById()</code> is still powerful, but it's not nearly as powerful as XPath. Here are some examples.


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


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


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


//get all the addresses that have "south" in the street name
// get all the addresses that have "south" in the street name
results = evaluate(fileContents,  "//address[contains(@street, 'south')]");  
results = evaluateXPath(people,  "//address[contains(@street, 'south')]");
alert(results.length);
</pre>
</pre>


==Resources==
==Resources==
* [http://www.w3schools.com/xpath/ Nice XPath Tutorial]
* [http://www.topxml.com/code/default.asp?p=3&id=v20021221025528 XPath Visualizer for Mozilla and Firefox]
* [http://www.topxml.com/code/default.asp?p=3&id=v20021221025528 XPath Visualizer for Mozilla and Firefox]
* [http://forums.mozillazine.org/viewtopic.php?t=229106 Forum discussion on this topic]
* [http://forums.mozillazine.org/viewtopic.php?t=229106 Forum discussion on this topic]


[[Category:Example code]]
[[Category:Example code]] [[Category:XML in Javascript]]

Revision as of 13:55, 10 March 2005

XPath is a language for addressing parts of an XML document. It is a W3C recommendation.

This article describes Mozilla interfaces exposing XPath functionality to Javascript code. It doesn't teach XPath itself, if you're unfamiliar with this technology, please refer to W3Schools XPath tutorial.

Wrapper function

The following function can be used to evaluate XPath expressions on given XML nodes. The first argument is a DOM node, while the second is a string defining an XPath expression.

Note that you shouldn't use this function if you expect to get a long list of results from it.

// evaluate an XPath expression aExpression against a given DOM node aNode, 
// returning the results as an array
// thanks wanderingstan at morethanwarm dot mail dot com
function evaluateXPath(aNode, aExpr) {
  var xpe = new XPathEvaluator();
  var result = xpe.evaluate(aExpr, aNode, xpe.createNSResolver(aNode.ownerDocument.documentElement),
                            0, null);
  var found = [];
  while (res = result.iterateNext())
    found.push(res);
  return found;
}

Sample Usage

Assume we have the following XML document (see also How to Create a DOM tree and Reading and Writing XML to and from DOM trees) and people is the <people> element:

<?xml version="1.0"?>
<people>
  <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>

  <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"/>
  </person>
</people>

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 = evaluateXPath(people, "//person/@last-name");
for (var i in results)
  alert("Person #" + i + " has the last name " + results[i].value);

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

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

// get all the addresses that have "south" in the street name
results = evaluateXPath(people,  "//address[contains(@street, 'south')]");
alert(results.length);

Resources