1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
|
---
title: Using XPath
slug: Using_XPath
tags:
- AJAX
- Code snippets
- DOM
- Extensions
- Transforming_XML_with_XSLT
- XPath
- 所有分类
translation_of: Web/XPath/Introduction_to_using_XPath_in_JavaScript
translation_of_original: Using_XPath
---
<p>
</p><p><a href="cn/XPath">XPath</a> is a language for addressing parts of an XML document. It is a <a class="external" href="http://www.w3.org/TR/xpath">W3C recommendation</a>.
</p><p>This article describes Mozilla interfaces exposing XPath functionality to JavaScript code. These are described in <a class="external" href="http://www.w3.org/TR/DOM-Level-3-XPath/">DOM Level 3 XPath</a> (which is W3C Working Group Note at this moment).
</p><p>This article does not attempt teach XPath itself. If you're unfamiliar with this technology, please refer to <a class="external" href="http://www.w3schools.com/xpath/">W3Schools XPath tutorial</a>.
</p><p>For a very simple XPath usage example, see: <a href="cn/Code_snippets/HTML_to_DOM#Using_a_hidden_XUL_iframe_.28complete_example.29">Code_snippets:HTML_to_DOM#Using_a_hidden_XUL_iframe_.28complete_example.29</a>
</p>
<h3 id="Node-specific_evaluator_function">Node-specific evaluator function</h3>
<p>The following function can be used to evaluate XPath expressions on given XML nodes. The first argument is a DOM node or Document object, while the second is a string defining an XPath expression.
</p>
<pre>// Evaluate an XPath expression aExpression against a given DOM node
// or Document object (aNode), returning the results as an array
// thanks wanderingstan at morethanwarm dot mail dot com for the
// initial work.
function evaluateXPath(aNode, aExpr) {
var xpe = new XPathEvaluator();
var nsResolver = xpe.createNSResolver(aNode.ownerDocument == null ?
aNode.documentElement : aNode.ownerDocument.documentElement);
var result = xpe.evaluate(aExpr, aNode, nsResolver, 0, null);
var found = [];
var res;
while (res = result.iterateNext())
found.push(res);
return found;
}
</pre>
<p>This function uses <code>new XPathEvaluator()</code>. That constructor is specific to Mozilla. Scripts used on a webpage which might be used by other browsers should instead replace the call to <code>new XPathEvaluator()</code> with the following fragment:
</p>
<pre> // XPathEvaluator is implemented on objects that implement Document
var xpe = aNode.ownerDocument || aNode;
</pre>
<p>In that case the creation of the <a href="cn/DOM/document.createNSResolver">XPathNSResolver</a> can be simplified as:
</p>
<pre> var nsResolver = xpe.createNSResolver(xpe.documentElement);
</pre>
<p>Note however that <code>createNSResolver</code> should only be used if you are sure the namespace prefixes in the XPath expression match those in the document you want to query (and that no default namespace is being used (though see <a href="cn/DOM/document.createNSResolver">DOM:document.createNSResolver</a> for a workaround)). Otherwise, you have to provide your own implementation of XPathNSResolver.
</p><p>If you are using <a href="cn/XMLHttpRequest">XMLHttpRequest</a> to read a local or remote XML file into a DOM tree (as described in <a href="cn/Parsing_and_serializing_XML">Parsing and serializing XML</a>), the first argument to <code>evaluateXPath()</code> should be <code>req.responseXML</code>.
</p>
<h4 id="Sample_usage">Sample usage</h4>
<p>Assume we have the following XML document (see also <a href="cn/How_to_Create_a_DOM_tree">How to Create a DOM tree</a> and <a href="cn/Parsing_and_serializing_XML">Parsing and serializing XML</a>):
</p>
<pre><?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>
</pre>
<p>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.
</p>
<pre>// 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);
</pre>
<h3 id="docEvaluateArray">docEvaluateArray</h3>
<p>The following is a simple utility function to get (ordered) XPath results into an array, when there is no special need for namespace resolvers, etc. It avoids the more complex syntax of <code><a href="cn/DOM/document.evaluate">document.evaluate()</a></code> for cases when it is not required as well as the need to use the special iterators on <code><a href="cn/XPathResult">XPathResult</a></code> (by returning an array instead).
</p>
<pre>// Example usage:
// var els = docEvaluateArray('//a');
// alert(els[0].nodeName); // gives 'A' in HTML document with at least one link
function docEvaluateArray (expr, doc, resolver) {
if (!doc) {
doc = document;
}
if (!resolver) {
resolver = null;
}
var result = doc.evaluate(expr, doc, resolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var a = [];
for(var i = 0; i < result.snapshotLength; i++) {
a[i] = result.snapshotItem(i);
}
return a;
}
</pre>
<h3 id="getXPathForElement">getXPathForElement</h3>
<p>The following function allows one to pass an element and an XML document to find a unique string XPath expression leading back to that element.
</p>
<pre>function getXPathForElement(el, xml) {
var xpath = '';
var pos, tempitem2;
while(el !== xml.documentElement) {
pos = 0;
tempitem2 = el;
while(tempitem2) {
if (tempitem2.nodeType === 1 && tempitem2.nodeName === el.nodeName) { // If it is ELEMENT_NODE of the same name
pos += 1;
}
tempitem2 = tempitem2.previousSibling;
}
xpath = "*[name()='"+el.nodeName+"' and namespace-uri()='"+(el.namespaceURI===null?'':el.namespaceURI)+"']["+pos+']'+'/'+xpath;
el = el.parentNode;
}
xpath = '/*'+"[name()='"+xml.documentElement.nodeName+"' and namespace-uri()='"+(el.namespaceURI===null?'':el.namespaceURI)+"']"+'/'+xpath;
xpath = xpath.replace(/\/$/, '');
return xpath;
}</pre>
<h3 id="Resources">Resources</h3>
<ul><li> <a href="cn/XPath">XPath</a>
</li><li> <a class="external" href="http://www.topxml.com/code/default.asp?p=3&id=v20021221025528">XPath Visualizer for Mozilla and Firefox</a>
</li><li> <a class="external" href="http://www.w3schools.com/xpath/">XPath tutorial</a>
</li><li> <a class="external" href="http://forums.mozillazine.org/viewtopic.php?t=229106">Forum discussion on this topic</a>
</li><li> <a class="external" href="http://zeus.jesus.cam.ac.uk/~jg307/mozilla/xpath-tutorial.html">Using the Mozilla JavaScript Interface to XPath</a> - draft tutorial on using XPath from javascript
</li><li> <a class="link-https" href="https://sourceforge.net/projects/sarissa/">Sarissa</a> - Sarissa is a cross-browser ECMAScript library for client side XML manipulation, including loading XML from URLs or strings, performing XSLT transformations, XPath queries and more. Supported: Gecko (Mozilla, Firefox etc), IE, KHTML (Konqueror, Safari). If you're writing JavaScript that is used in both XUL applications and HTML pages, and the HTML pages may be viewed in non-Gecko-based applications (such as Internet Explorer, Opera, Konqueror, Safari), you should consider using Sarissa to parse and/or serialize XML. <i>Note:</i> Do not create a DOM object using <code>document.implementation.createDocument()</code> and then use Sarissa classes and methods to manipulate that object. It will not work. You must use Sarissa to create the initial DOM object.
</li></ul>
<h2 id="See_also">See also</h2>
<ul><li> <a href="cn/Introduction_to_using_XPath_in_JavaScript">Introduction to using XPath in JavaScript</a>
</li></ul>
<div class="noinclude">
</div>
{{ languages( { "fr": "fr/Utilisation_de_XPath", "ja": "ja/Using_XPath", "en": "en/Using_XPath", "ko": "ko/Using_XPath" } ) }}
|